Laravel查询使用database ase.php Strict=>false。如何使其与Strict=>true一起工作? [英] Laravel query works with database.php strict=>false. How to make it work with strict=>true?

查看:20
本文介绍了Laravel查询使用database ase.php Strict=>false。如何使其与Strict=>true一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

strict => false位于database.php的Laravel中时,有一个查询可以工作。我不想创建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();

启用严格模式时出错

语法错误或访问冲突:选择列表的1055表达式#1 不在GROUP BY子句中,并且包含非聚合列 "Transaction_allocations.id",它在功能上不依赖于 GROUP BY子句中的列;这与 SQL_MODE=ONLY_FULL_GROUP_BY(SQL:SELECT*FROMtransactionsWHERE contact_id=9且存在(SELECT*FROMtransaction_allocations 其中transactions.id=transaction_allocations.transaction_idtransaction_allocations.deleted_at为NULL GROUP BY transaction_id是否有交易。贷方&>金额(金额)) EXISTS(SELECT*FROMtransaction_allocationsWHERE transactions.id=transaction_allocations.transaction_idtransaction_allocations.deleted_at为空))

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

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

含义:获取transaction.Credit字段大于相关表(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严格模式语句要求所有非聚合字段(COUNTSUMMAX等)在SELECT语句中出现在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');
})

这篇关于Laravel查询使用database ase.php Strict=>false。如何使其与Strict=>true一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆