【问题标题】:Laravel query where column value is greater than sum of related model column valuesLaravel 查询,其中列值大于相关模型列值的总和
【发布时间】: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 transactions where contact_id = 9 并且存在(select * from transaction_allocations where transactions.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


【解决方案1】:

我认为使用 Raw 比较两列更好。

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

如果查询失败,则尝试在database.php 中使用'strict' => false 进行mysql 连接

【讨论】:

  • 这个答案需要'strict'=>false。以下答案解释了如何避免严格 => 错误。 stackoverflow.com/a/68047726/6684758
  • 尝试使用此查询并收到错误:SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'cargo.application_transfers.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
猜你喜欢
  • 2023-01-30
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多