嗨,我正在使用 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)
我该如何解决?
答案 0 :(得分:0)
您可以在 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 添加到查询中以避免严格模式错误。