Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel Eloquent Join with SUM()

I am trying to convert MySQL query to Laravel Eloquent, but it is throwing error.
The query is like this:

(
    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
);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();

Using the syntax in your comment:

$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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading