Laravel/雄辩的hasMany关系sum() [英] Laravel / Eloquent hasMany relationship sum()

查看:424
本文介绍了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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆