Laravel Eloquent - Как суммировать поля внутри столбца отношения? - PullRequest
1 голос
/ 10 апреля 2020
  I need to sum every paid_amount inside of each expense_payment_liab instead of returning all these 
 individual  paid_amount  as it can be seen in images for clear view.So far my query looks like this:
 Model Relation is like Voucher has many Expenses and Expenses has many Expensepaymentliab.       

  This is so far what I tried:
    $expense = Voucher::where('voucher_date', $request->date)
        ->where('account_id', 1)
        ->with(['expenses' => function ($expense) use ($date) {
            $expense->with(['expPaymentLiab' => function ($inner) use ($date) {
                return $inner->select('paid_amount', 'expense_id')->where('paid_date', '=', $date);
                //need to return the sum of paid_amount.
                // I've  also tried this
                 //$inner->sum('paid_amount')
                // $inner->sum('paid_amount', 'expense_id')
             }]);
            $expense->select('id', 'date', 'total_amount', 'voucher_id');
        }])->get();

Эти изображения, пожалуйста, проверьте

Необходимо сложить такое поле paid_amount.

1 Ответ

1 голос
/ 10 апреля 2020

Вы можете использовать withCount для суммирования поля paid_amount.

Voucher::where('voucher_date', $request->date)
        ->where('account_id', 1)
        ->with(['expenses' => function ($expense) use ($date) {
            // select the columns first, so the subquery column can be added later.
            $expense->select('id', 'date', 'total_amount', 'voucher_id');
            $expense->withCount(['expPaymentLiab AS paid_sum' => function ($query) use ($date) {
                return $query->select(DB::raw('SUM(paid_amount)'))->where('paid_date', '=', $date);
             }]);
        }])
        ->get();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...