Laravel 查询适用于 database.php strict=>false。如何让它与 strict=>true 一起工作?

Laravel query works with database.php strict=>false. How to make it work with strict=>true?

有一个查询在 Laravel 的 database.phpstrict => false 时有效。我不想 strict => false,我希望它保持 true

有没有办法更改此查询并获得相同的结果?

Transaction::where('contact_id', 9)
    ->with('allocations')
    ->whereHas("allocations", function ($query) {
        $query->havingRaw('transactions.credit > sum(amount)');
        $query->groupBy('transaction_id');
    })
    ->orDoesntHave("allocations")
    ->get();

启用严格模式时出错

Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'transaction_allocations.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from transactions where contact_id = 9 and exists (select * from transaction_allocations where transactions.id = transaction_allocations.transaction_id and transaction_allocations.deleted_at is null group by transaction_id having transactions.credit > sum(amount)) or not exists (select * from transaction_allocations where transactions.id = transaction_allocations.transaction_id and transaction_allocations.deleted_at is null))

上下文: 有两个 tables transactionstransaction_allocations。一个事务可以有多个分配。

我正在尝试查找未完全分配的交易。

含义:获取 transaction.credit 字段大于相关 table(transaction_allocations) 中该交易金额总和的交易。

交易模型

Schema::create('transactions', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->timestamps();
    $table->foreignId('contact_id')->constrained();
    $table->decimal('credit', 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);
}
严格模式下的

GROUP BY语句要求[=15=中的所有非聚合字段(COUNTSUMMAX等) ] 语句出现在 GROUP BY.

如错误所示,whereHas() 方法产生了一个 select * 查询,但是,您的 GROUP BY 语句只有 transaction_id.

要解决此问题,您只需将 select('transaction_id') 添加到 whereHas 调用中即可:

->whereHas("allocations", function ($query) {
    $query->select('transaction_id')
        ->havingRaw('transactions.credit > sum(amount)')
        ->groupBy('transaction_id');
})