Laravel / Eloquent hasMany 关系 sum()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27680367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel / Eloquent hasMany relationship sum()
提问by mbklnd
I can't figure out how to eager load a sum of a relationships columns.
我不知道如何急切加载关系列的总和。
Database (simplified) is as follows;
数据库(简体)如下;
TABLES
表
PRODUCT PRODUCT_VARIATIONS
*ID* *ID*
*NAME* *NAME*
*AVAILABLE_STOCK*
I have my relationships set up as follows;
我的关系建立如下;
public function variations()
{
return $this->hasMany('Product_variation');
}
When loading all Products I want to be able to see the SUM of all stock for that product attached to the product object itself.
加载所有产品时,我希望能够看到附加到产品对象本身的该产品的所有库存的总和。
A product may have many variations.
一个产品可能有很多变化。
I can return the entire INDIVIDUAL variations attached to the products (See Below)
我可以退回产品附带的整个 INDIVIDUAL 变体(见下文)
$products = Product::with('variations')->paginate(15);
but I just want to return all the products with a simple integer showing their available_stock count taking into account all variations.
但我只想用一个简单的整数返回所有产品,显示它们的 available_stock 计数,并考虑到所有变化。
I want to be able to type
我希望能够打字
@foreach ($products as $product)
$product->available_stock // Returns INT
@endforeach
采纳答案by mbklnd
OK, thanks for your answer @joseph, now I know I was on a wild goose chase.
好的,谢谢@joseph 的回答,现在我知道我正在疯狂追逐。
Solved the problem with an unattractive foreach
用没有吸引力的 foreach 解决了问题
$products = Product::with('variations')->remember(2)->paginate(15);
foreach ($products as $product) {
$i = 0;
foreach ($product->variations as $variation)
{
$i = $i + $variation->available_stock;
}
unset($product->variations);
$product->available_stock = $i;
}
回答by Joseph Silber
Eloquent does not natively support relation count eager loading.
Eloquent 本身不支持关系计数预加载。
Read this article on how to implement it yourself:
阅读这篇关于如何自己实现它的文章:
回答by Jarek Tkaczyk
The thing is, you don't want count
, but sum
. So here's what you need, just like in my article that @Joseph linked, only with different aggregate function:
问题是,你不想要count
,但是sum
。所以这就是你需要的,就像我在@Joseph 链接的文章中一样,只有不同的聚合函数:
public function availableStock()
{
return $this->hasOne('Product_variation')
->selectRaw('product_id, sum(available_stock) as aggregate')
->groupBy('product_id');
}
public function getaAvilableStockAttribute()
{
if ( ! array_key_exists('availableStock', $this->relations)) {
$this->load('availableStock');
}
$relation = $this->getRelation('availableStock');
return ($relation) ? $relation->aggregate : null;
}
Then you can do what you asked for:
然后你可以做你要求的:
$products = Product::with('availableStock')->get();
$products->first()->availableStock; // '155' | null
// or simply
Product::first()->availableStock; // '155' | null