Laravel eloquent sum 关系量和groupby

标签 laravel eloquent

产品表:

id        name
1     first product

product_credits 表:
id   product_id   quantity
1         1          10
2         1          20

我正在尝试做的事情:

我正在尝试获取所有 产品数量 .

预期数据:

获取:
  • 产品名称 = 第一个产品
  • 产品数量 = 30

  • 模型关系代码:
    public function credits () {
        return $this -> hasMany('App\Models\Product\ProductCredits')
            -> whereHas('importInvoice', function ($query) {
                $query->where('deleted_at', null);
            }) -> orderBy('created_at', 'ASC') -> orderBy('quantity', 'DESC');
    }
    

    关系运作良好。

    我尝试过的:

    我曾尝试使用 with在 Eloquent 中发挥作用。
    public function exportProductsCredit(Request $request) {
        // GET THE COLLECTION
        $products = Product::with(['credits' => function ($query) {
            $query -> where('quantity', '>', 1) -> groupBy('product_id') -> sum('quantity');
        }]) -> get();
    
        return $products;
    }
    

    但它抛出一个错误:product_credits.id' isn't in GROUP BY
    编辑

    问题是我有 Mutator我想显示的字段,例如我计算 product_net_price我作为突变器返回。

    最佳答案

    如果您希望将其作为属性,请不要尝试像关系一样查询构建它。

    您可以在 Product::class 中声明这样的属性

    public function getSumCreditsAttribute()
    {
        return $this->credits->where('quantity', '>', 1)->sum('quantity');
    }
    

    您也可以随时使用 appends 加载它属性
    protected $appends = ['sum_credits'];
    

    或者当您有 Product::class 的实例时访问它
    $products = Product::get();
    foreach ($products as $product) {
        var_dump($product->sum_credits);
    }
    

    关于Laravel eloquent sum 关系量和groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56832512/

    相关文章:

    php - Laravel 5.2 - Metatag 规范 URL

    php - 将某一行设置为 1,其他设置为 0 用 Eloquent 表达

    laravel - 从路径 Laravel 5 渲染 View

    php - 比较 Laravel Eloquent Result 并获取日期

    php - Laravel使用 Eloquent 关系选择链接表的最后一行

    php - Eloquent |使用 with() 导致返回 NULL

    php - Laravel Eloquent 仅选择不用作外键的数据

    php - laravel Eloquent 关系与基于外部列的 where 子句

    laravel - HasManyThrough 具有一对多关系

    php - 如何将 laravel 6 升级到 7