在 Laravel 中的 whereRaw 中求和我该如何解决?

嗨,我正在使用 eloquent 进行查询,以获取包含 100 多种产品的所有发票的 ID,这就是我正在尝试的:

 $products = Product::whereRaw('sum(quantity) >= 100')->pluck('invoice_id');

我收到此错误:

Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1111 Invalid use of group function (SQL: select `invoice_id` from `products` where sum(quantity) >= 100)

我该如何解决?

g455484794 回答:在 Laravel 中的 whereRaw 中求和我该如何解决?

您可以在 having 中使用 whereHas 语句。

$invoices = Invoice::whereHas('products',fn($q) => $q->select('quantity')->havingRaw('SUM(quantity) >= 100')->groupBy('quantity'))->get();

或者,没有箭头功能(我知道有些人很可怕:)):

$invoices = Invoice::whereHas('products',function($query){
    return $query->select('quantity')
        ->havingRaw('SUM(quantity) >= 100')
        ->groupBy('quantity');
})->get();

Select 和 groupBy 添加到查询中以避免严格模式错误。

本文链接:https://www.f2er.com/400.html

大家都在问