我正在嘗試將 MySQL 查詢轉換為 Laravel Eloquent,但它拋出錯誤。查詢是這樣的:
(
SELECT
p.id AS product_id,
p.name AS product_name,
SUM(s.quantity) AS product_quantity
FROM
products AS p
INNER JOIN
stocks AS s
ON p.id = s.product_id
GROUP BY
p.id
);
uj5u.com熱心網友回復:
DB::query()
->select(
'p.id AS product_id',
'p.name AS product_name',
)
->selectRaw('SUM(s.quantity) AS product_quantity') // need to use selectRaw for aggregate values like this.
->from('products', 'p')
->join('stocks as s', 'p.id', 's.product_id')
->groupBy('p.id')
->get();
使用評論中的語法:
$this->model
->select("products.id as product_id", "products.name as product_name")
->selectRaw("SUM(quantity) as product_quantity") // select() doesn't work for aggregate values
->join("products", "products.id", "=", "stocks.product_id")
->groupBy("products.id")
->get()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/377387.html
上一篇:即使該列沒有資料,如何顯示列名?
下一篇:重命名sql表中的欄位的問題
