Laravel/雄辩的hasMany关系sum()

编程入门 行业动态 更新时间:2024-10-18 19:26:46
本文介绍了Laravel/雄辩的hasMany关系sum()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不知道如何急于加​​载一个关系列的总和.

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()

本文发布于:2023-10-24 20:13:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524891.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:雄辩   关系   Laravel   sum   hasMany

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!