【问题标题】:Laravel Eloquent Join with SUM()Laravel Eloquent 加入 SUM()
【发布时间】:2022-01-13 15:22:08
【问题描述】:

我正在尝试将 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
);

【问题讨论】:

  • 能把雄辩和错误加起来吗?
  • $stocks = $this->model->select("products.id as product_id", "products.name as product_name", "SUM(quantity) as product_quantity") ->join(" products", "products.id", "=", "stocks.product_id") ->get() ->groupBy("products.id");
  • 错误是:SQLSTATE[42S22]:找不到列:1054 '字段列表'中的未知列'SUM(数量)'(SQL:选择products.idproduct_idproducts.name as product_name, SUM(quantity) as product_quantity from stocks inner join products on products.id = stocks.@9876)
  • 问题很简单,聚合列使用selectRaw即可(SUM(quantity) AS product_quantity)。
  • 从错误中可以看出,您没有在 eloquent 中指定数量表,这就是导致错误的原因。所以用雄辩的方式修改它,我认为它会起作用

标签: mysql laravel eloquent


【解决方案1】:
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()

【讨论】:

    猜你喜欢
    • 2014-04-17
    • 2017-07-23
    • 2014-03-07
    • 2018-08-16
    • 2021-10-22
    • 2021-07-03
    • 2022-01-25
    • 1970-01-01
    • 2022-10-04
    相关资源
    最近更新 更多