【问题标题】:Laravel query works with database.php strict=>false. How to make it work with strict=>true?Laravel 查询适用于 database.php strict=>false。如何使它与strict => true一起工作?
【发布时间】:2021-09-03 21:45:41
【问题描述】:

strict => false 在 Laravel 的 database.php 中时,有一个查询有效。我不想让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 Expression #1 of SELECT list 不在 GROUP BY 子句中并且包含非聚合列 'transaction_allocations.id' 在功能上不依赖于 GROUP BY 子句中的列;这与 sql_mode=only_full_group_by (SQL: select * from transactions where contact_id = 9 并且存在(从 transaction_allocations 中选择 * 其中transactions.id = transaction_allocations.transaction_idtransaction_allocations.deleted_at 是空组 transaction_id 是否有 transactions.credit > sum(amount)) 存在 (select * from transaction_allocations where transactions.id = transaction_allocations.transaction_idtransaction_allocations.deleted_at 为空))

上下文: 有两个表 transactionstransaction_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);
}

【问题讨论】:

  • 启用严格模式时会显示哪个错误?
  • 错误添加到问题。

标签: laravel eloquent laravel-8 eloquent-relationship


【解决方案1】:

严格模式下的GROUP BY 语句要求SELECT 语句中的所有非聚合字段(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');
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多