0

Mysql query like this :

SELECT a.id, a.name, b.TotalMeal, c.TotalCollection
FROM users a
LEFT JOIN (
    SELECT user_id, SUM( breakfast + dinner + lanch ) AS TotalMeal
    FROM meals
    GROUP BY user_id) b ON a.id = b.user_id
LEFT JOIN (
    SELECT user_id, SUM( amount ) AS TotalCollection
    FROM collections
    GROUP BY user_id) c ON a.id = c.user_id
LIMIT 0, 30

I want to convert it to Laravel eloquent, but I'm confused. I have Three tables. eg - users( id, name,email ..), meals( user_id, breakfast,lanch,dinner) and collections(user_id, amount) .

1
  • You should use relations if you don't want to use joins. If you need joins, then this is the correct way.enter link description here Commented Apr 7, 2019 at 15:13

1 Answer 1

0

There is a little hack that uses withCount() to select sums of related tables which can be used in your scenario:

User::query()
    ->select([
        'id',
        'name',
    ])
    ->withCount([
        'meals as total_meals' => function ($query) {
            $query->select(DB::raw('SUM(breakfast + dinner + lunch)'));
        },
        'collections as total_collections' => function ($query) {
            $query->select(DB::raw('SUM(amount)'));
        },
    ])
    ->get();

In this query, withCount will perform the joins for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.