2017-02-12 49 views
0

我有一个表供应商,与子表1许多产品。我想复制此查询的结果在Breeaze:Breeze框架 - 如何做内联子表计数查询

SELECT *, 
(select count(*) from Product where Supplier.id = Product.SupplierId) ProductCount 
FROM Supplier 

基本上,我想有供应商的数据列的输出,与供应商的产品数量的附加列。

我目前在Breeze中有这个查询给我供应商,但我没有看到一种方法来将count列添加到结果中。我已经在Entity ProductCount和NonMappable中包含了一个字段:

var query = _repository.Suppliers.AsQueryable(); 
      if (supplierIds.Length > 0) 
      { 
       query = query.Where(supplier => supplierIds.Contains(supplier.Id)); 
       var result = query.ToList(); 
      } 
      return query; 

我在想什么?有没有办法在微风或不这样做呢?

感谢您的协助!

+0

你可以尝试添加该服务器端的计算性能,以实体的模型,然后添加属性的实体构造(不是初始化程序)客户端,所以计算的属性从服务器返回。 – Jonathan

回答

1

看一看在微风查询结构的inlineCount属性:

successFunction([data]) { 
    .... 
} 

你可以得到:

结果:查询字段(阵列)

inlineCount: 仅当'inlineCount(true)'应用于查询时才可用。返回在应用任何跳过或运算符之前,但在应用了任何过滤器/谓词之后,查询返回的项目数。

例如:

var query = new EntityQuery("Clients") 
    .where("ClientName", "startsWith", "B") 
    .take(20) 
    .orderBy("ClientName") 
    .inlineCount(true); 

结果

query.execute().then(function(data) { 
data.results 
data.inlineCount 
} 

data.inlineCount列将返回12,如果你的查询中包含12个客户开始使用 “B” 即使总返回的记录可能累计为20.

+0

我在文档中看到了这个函数。它接近但不是我所需要的。 我有一个包含多个产品的供应商对象。我需要供应商的专栏,列中包含属于该供应商的产品数量。 –

0

如果您已有ProductCount您的供应商实体的财产,您只需要从服务器返回它。如果ProductCount是在服务器端实体填充,您可以在服务器和客户端的属性将只是工作:

[HttpGet] 
public IQueryable<Supplier> SuppliersWithProductCount() 
{ 
    var query = _repository.Suppliers.AsQueryable(); 
    // ...add server-side params to the query, if desired... 

    // Get objects with the supplier and the count 
    var list = query.Select(s => new { Supplier = s, Count = s.Products.Count }).ToList(); 
    // Set the count on the Supplier 
    list.ForEach(o => o.Supplier.ProductCount = o.Count); 
    // Extract the Suppliers 
    var suppliers = list.Select(o => o.Supplier); 
    return suppliers.AsQueryable(); 
} 

在另一方面,如果ProductCount财产只有客户端上存在,您需要将其分别传递给客户端,并在查询结果处理程序中将客户端实体的属性设置为。
在服务器上:

[HttpGet] 
public IQueryable<Object> SuppliersWithProductCount() 
{ 
    var query = ContextProvider.Context.Suppliers.AsQueryable(); 
    // ...add server-side params to the query, if desired... 

    // Get objects with the supplier and the count 
    return query.Select(s => new { Supplier = s, Count = s.Products.Count }); 
} 

在客户端:

EntityQuery.from("SuppliersWithProductCount") 
    .using(myEntityManager).execute() 
    .then(function (data) { 
     // results are { Supplier, Count } objects 
     var results = data.results; 
     var suppliers = []; 
     results.forEach(function (r) { 
      r.Supplier.ProductCount = r.Count; 
      suppliers.push(r.Supplier); 
     }); 
     return suppliers; 
    });