Laravel 具有多个 where 子句的查询范围 returns 不正确的数据

Laravel query scope with multiple where clauses returns incorrect data

我有以下 table consols:

Schema::create('consols', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->double('current_weight', 8, 3)->default(0);
    $table->double('current_weight', 8, 3)->default(0);
    $table->double('final_weight', 8, 3)->default(0);
    $table->double('final_cbm', 8, 3)->default(0);    
    $table->timestamp('finals_sent', 0)->nullable();
});

其中包含如下条目:

id | current_weight | current_cbm | final_weight | final_cbm | finals_sent         |
-----------------------------------------------------------------------------------|
1  | 45.000         | 1.000       | 200.000      | 10.000    | 2019-09-26 10:03:59 |

我在我的模型 Consol 上写了一个范围来过滤条目,其中:finals_sent 不为空,current_weight > final_weightcurrent_cbm > final_cbm:

public function scopeOfCurrentGreaterThanFinals($query)
{
    return $query->whereNotNull('finals_sent')->where(function ($query) {
        $query->where('current_weight', '>', 'final_weight')
            ->orWhere('current_cbm', '>', 'final_cbm');
    });

}

当我使用它并将其转储出来时 - 我希望看到 no 结果:

$consols = Consol::ofCurrentGreaterThanFinals()
           ->orderBy('awb', 'DESC')
           ->get()
           ->toArray();

但是,上面的条目仍然显示:

array:1 [▼
  0 => array:24 [▼
    "id" => 1
    "current_weight" => 45.0
    "current_cbm" => 1.0
    "final_weight" => 200.0
    "final_cbm" => 10.0
    "finals_sent" => "2019-09-26 10:03:59"
  ]
]

我不确定我做错了什么?我想我清楚地表明我只想看到结果,其中:

和上面的条目不适合这个,因为current_weight和current_cbm显然不高于final_weight和final_cbm。

我做错了什么?

好的,问题来了。为了比较这两列,您必须使用 whereRaw() 作为第二个参数的 where 需要一个值,而不是列。 所以这应该有效,我用你的数据库和值进行了测试。

return $query->whereNotNull('finals_sent')->where(function ($q) {
            $q->whereRaw('current_weight > final_weight')
                ->orWhereRaw('current_cbm > final_cbm');
        });