php - 如何获取关系数据库中列的总和 "Laravel5"

标签 php mysql laravel eloquent

我希望有人能帮助我解决我的问题。我正在处理 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.
        ]
    }
}]

最佳答案

您可以使用修改后的 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 访问总和:

关于php - 如何获取关系数据库中列的总和 "Laravel5",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49004334/

相关文章:

php - session 和PHP重定向不起作用

php - 错误的 ELF 类 - PHP 扩展

php - 自动检测语言并重定向用户

php - Laravel-5 添加 hasRole 方法到 Auth

php - 在原始查询中从 Laravel 5.2 DB 返回主键

php - SQL Server 错误 1934 发生在 INSERT 到具有计算列 PHP/PDO 的表中

php - Yii2 连接多个表的关系

mysql - 使用自增主键插入记录

c++ - C++ mysql sqlstring崩溃0xC0000005无法读取内存

php - 需要 Laravel 移动应用程序的推送服务