如何从关系 table 中获取具有连接的列的总和?
How to take sum of column with join from relationship table?
我正在尝试获取 table 费用中的列收入总和。收费 table 与寄售有 belongsTo
关系,寄售与收费有 hasMany
关系。现在的情况是我正在尝试计算收入列的总和,其中 invoice_id
是 63.
这是我的努力。
Consignment::where('invoice_id', 63)->join('charges', 'charges.object_id', '=', 'consignments.id')
->where('charges.model', '=', 'Consignment')
->groupBy('consignments.id')
->get(['consignments.id', DB::raw('sum(charges.income) as income')])
->sum('income');
不知道怎么回事
使用关系更容易。试试这个:
$sum = Charge::query()->whereHas('consignment', function ($query) {
$query->where('invoice_id', 63);
})->sum('income');
您可以在$result中获取查询结果并使用。
collect($result)->pluck('income')->sum()
我正在尝试获取 table 费用中的列收入总和。收费 table 与寄售有 belongsTo
关系,寄售与收费有 hasMany
关系。现在的情况是我正在尝试计算收入列的总和,其中 invoice_id
是 63.
这是我的努力。
Consignment::where('invoice_id', 63)->join('charges', 'charges.object_id', '=', 'consignments.id')
->where('charges.model', '=', 'Consignment')
->groupBy('consignments.id')
->get(['consignments.id', DB::raw('sum(charges.income) as income')])
->sum('income');
不知道怎么回事
使用关系更容易。试试这个:
$sum = Charge::query()->whereHas('consignment', function ($query) {
$query->where('invoice_id', 63);
})->sum('income');
您可以在$result中获取查询结果并使用。
collect($result)->pluck('income')->sum()