Laravel雄辩的查询,其中包含来自另一个表中的条件的值的总和



我有两个表。交易和分配。 一个事务可以有多个分配。 关系定义如下:

内部分配表

class Allocation extends Model
{
public function transaction_fk(){
return $this->belongsTo('AppModelsTransaction','transaction_id');
}
}

交易表内

class Transaction extends Model
{
public function allocations() {
return $this->hasMany('AppModelsAllocation');
}
}

如果事务总计不等于分配总计的总和,我需要查询事务表中具有特定 ID 的所有行以及该事务行的分配总和以及分配总计的总和。大致如下:

Transaction::where('id',$id)->where('amount','!==','sum(allocations.amount)')->with('balance' as 'sum(allocations.amount)')->get();

此查询不起作用。我错过了什么?

我能够将其作为一个简单的查询来执行,我循环了该查询并进行了第二个查询并添加到列表中。它给了我正确的结果。如您所见,这是冗长且较慢的。我需要在查询数据库一次时立即执行此操作。

$transactions2 = Transaction::where('contact_type','supplier')
->where('contact_id',$ehead->supplier_id)
->get();
$transactions = [];
foreach ($transactions2 as $item) {
$sum = Allocation::where('transaction_id',$item['id'])->get()->sum('amount');
if($item['amount'] !== $sum){
$item->unallocated_amount = $sum;
array_push($transactions, $item);
}
}

如果要在单个查询中执行此操作,则必须使用 groupBy 和聚合函数。

$items = Transaction::query()
->join('allocations', 'transactions.id', '=', 'allocations.transaction_id')
->groupBy('transactions.id')
->having('transactions.amount', '<>', 'sum(allocations.amount)')
->whereIn('transactions.id', $transactions2)
->select('transactions.*')
->get();

最新更新