【发布时间】:2021-09-03 20:41:41
【问题描述】:
我有两个表 transactions 和 transaction_allocations。一笔交易可以有多个分配。
交易模型
Schema::create('transactions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->foreignId('contact_id')->constrained();
$table->decimal('amount',19,4)->nullable();
});
分配模型
Schema::create('transaction_allocations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamp('created_at');
$table->foreignId('transaction_id')->nullable()->constrained();
$table->foreignId('bill_id')->nullable()->references('id')->on('bills');
$table->decimal('amount',19,4)->nullable();
});
交易模型中的关系
public function allocations(){
return $this->hasMany(TransactionAllocation::class);
}
我需要查询交易金额大于该交易的所有分配金额总和的所有交易。 (基本上是找到未分配余额的交易)。
Transaction::where('contact_id',$id)->where('amount','>',sum of allocations)->get();
我如何实现它?
我能够创建一个访问器来执行此计算并找到未分配的金额。但似乎访问器不能在哪里使用。我不想加载所有交易然后过滤它,因为它会太多。
我想直接查询和获取过滤的行。我该怎么做?
【问题讨论】:
-
Transaction::where('contact_id',$id) ->with('allocations') ->whereHas("allocations",function ($query){ $query->haveRaw('transactions .amount>sum(amount)')->groupBy('transaction_id'); }) ->get();
-
试了查询,出现如下错误。下一条评论出错。
-
SQLSTATE[42000]:语法错误或访问冲突:1055 SELECT 列表的表达式 #1 不在 GROUP BY 子句中,并且包含在功能上不依赖于 GROUP 中的列的非聚合列“transaction_allocations.id” BY 子句;这与 sql_mode=only_full_group_by 不兼容(SQL:select * from
transactionswherecontact_id= 9 并且存在(select * fromtransaction_allocationswheretransactions.id=transaction_allocations.transaction_id和 @987654332 @.deleted_at是空组transaction_id具有 transactions.amount > sum(amount))) -
尝试一次 'strict' => false,在 database.php 中用于 mtsql
-
试过了。它给了我空。应该给出一个结果。
标签: laravel eloquent laravel-8 eloquent-relationship