【问题标题】:How to get the SUM of a column in a relational database "Laravel5"如何获取关系数据库“Laravel5”中列的总和
【发布时间】:2018-02-27 08:35:54
【问题描述】:

我希望有人可以帮助我解决我的问题。我对 Laravel 5 的这个小关系问题很感兴趣。

问题:

我想在“钱包”模型中获取我的“金额”列的总和。

我当前正在运行的代码。

public function children()
{        
    return  $this->hasMany('App\Tree', 'parent_id','id')
                 ->with('children')
                 ->with('user')
                 ->with('user.wallets');
}

注意:此返回带有以下数据。

[{
    ...,
    children: [...]
    user: {
        ...,
        wallets: [...] // return list of array
    }
}]

我的解决方案,但没有运气。

return  $this->hasMany('App\Tree', 'parent_id','id')
                     ->with('children')
                     ->with('user')
                     ->with('user.wallets', function($q) {
                        $q->sum('amount');
                     });

想要的结果

[{
    ...,
    children: [...]
    user: {
        ...,
        wallets: [
            ...,
            amount: XXX.XX // e.g The total sum of the column, could be any number based on the sum of the column.
        ]
    }
}]

【问题讨论】:

  • 您还在寻找答案吗?
  • 你好@JonasStaudenmeir 是的,你知道这个问题的任何解决方案吗?

标签: php mysql laravel eloquent


【解决方案1】:

您可以使用修改后的withCount()。更改您的 userchildren 关系:

public function user()
{
    return $this->belongsTo('App\User')
        ->withCount(['wallets as wallets_amount' => function($query) {
            $query->select(DB::raw('sum(amount)'));
        }]);
}

public function children()
{        
    return $this->hasMany('App\Tree', 'parent_id', 'id')
        ->with('children', 'user');
}

然后您可以使用$user->wallets_amount 访问总和:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 2018-03-15
    • 2015-08-03
    • 1970-01-01
    • 2013-03-22
    • 2020-02-28
    • 1970-01-01
    • 2016-10-20
    相关资源
    最近更新 更多