Laravel - 只用一个请求来总结所有children.balance列的total_balance的方法?

时间:2016-11-01 13:09:56

标签: laravel laravel-query-builder

我需要简化数据结构化。我想获得父帐户子帐户中的余额总和。以下是我的对象的结构:

  • 帐户类型
    • 儿童类型
      • 帐户1(余额为9000)
      • 帐户2(余额为5000)

我希望获得所有子帐户的总余额:

  • 帐户类型
    • 儿童类型 - total_balance = 14000

如何在不循环访问对象的情况下执行此操作,但仅使用Laravel的查询构建器?

这是我控制器中的请求:

    $user = \Auth::user()->id;
    $accounts = AccountType::where('parent_id', 0)
    ->where('virtual', '=', 0)
    ->with(['children', 'children.accounts' => function ($query) use ($user) {
        $query->where('user_id', '=', $user);
    }])
    ->get();

    return $accounts;

这是我得到的对象:

{
"id": 1,
"name": "Savings",
"parent_id": 0,
"virtual": 0,
"created_at": "2016-10-27 10:28:59",
"updated_at": "2016-10-27 10:28:59",
"children": [
  {
    "id": 2,
    "name": "General Savings",
    "parent_id": 1,
    "virtual": 0,
    "created_at": "2016-10-27 10:28:59",
    "updated_at": "2016-10-27 10:28:59",
    "accounts": [
      {
        "id": 25,
        "institution_id": 0,
        "balance": 9000,
        "account_nickname": "Money Laundering",
        "is_primary": 1,
        "account_type_id": 2,
        "user_id": 2,
        "created_at": "2016-10-31 16:47:23",
        "updated_at": "2016-10-31 16:47:23"
      },
      {
        "id": 26,
        "institution_id": 0,
        "balance": 5000,
        "account_nickname": "Moneymarket Savings",
        "is_primary": 0,
        "account_type_id": 2,
        "user_id": 2,
        "created_at": "2016-10-31 16:48:30",
        "updated_at": "2016-10-31 16:48:30"
      }
    ]
  }
]

有办法吗?

1 个答案:

答案 0 :(得分:0)

这应该会为您提供一个列表,其中列出了每个account_type下包含total_balance所有帐户的用户所拥有的所有帐户类型:

$userAccountTypes = DB::table('account_types AS at')
    ->select(DB::Raw('*, SUM(a.balance) AS total_balance'))
    ->join('account_types AS ct', 'ct.parent_id', '=', 'at.id')
    ->join('accounts AS a', 'a.account_type_id', '=', 'ct.id')
    ->where('at.parent_id', 0)
    ->where('a.user_id', $user)
    ->groupBy('ct.id')
    ->get();