我不知道如何急于加载一个关系列的总和.
I can't figure out how to eager load a sum of a relationships columns.
数据库(简体)如下;
Database (simplified) is as follows;
表格
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.
产品可能有很多变化.
我可以退还产品附带的全部个人"变体(请参见下文)
I can return the entire INDIVIDUAL variations attached to the products (See Below)
$products = Product::with('variations')->paginate(15);但是我只想返回所有带有一个简单整数的产品,其中要考虑所有变化,以显示其available_stock计数.
but I just want to return all the products with a simple integer showing their available_stock count taking into account all variations.
我希望能够输入
@foreach ($products as $product) $product->available_stock // Returns INT @endforeach推荐答案
好的,谢谢你的回答@joseph,现在我知道我在追赶大雁.
OK, thanks for your answer @joseph, now I know I was on a wild goose chase.
使用无吸引力的foreach解决了问题
Solved the problem with an unattractive 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; }更多推荐
Laravel/雄辩的hasMany关系sum()
发布评论