Ivan Pirus
Ivan Pirus

Reputation: 1076

How do I create a query in Laravel 5.2 query builder, group join

I have the following sql PDO query.

("SELECT
    actual_remains.quantity,
    ingredients.name,
    ingredients.unit,
    ingredients.id
        FROM
           actual_remains
        LEFT JOIN
    ingredients ON ingredients.id = actual_remains.ingredient
        WHERE
    actual_remains.shop = ".$shopNumber);

How would I make this query in laravel query builder?

Upvotes: 1

Views: 330

Answers (1)

Bill Garrison
Bill Garrison

Reputation: 2227

Here is the straight Query builder way to write this (See Laravel Docs for more information):

$actualRemains = DB::table('actual_remains')
            ->leftJoin('ingredients', 'actual_remains.ingredient', '=', 'ingredients.id')
            ->select('actual_remains.quantity', 'ingredients.name', 'ingredients.unit', 'ingredients.id')
            ->where('actual_remains.shop', '=', $shopNumber)
            ->get();

If you create models and set their relationships you will probably have something more like this:

(new App\ActualRemain)->find($shopNumber)->with('ingredients');

See Laravel Docs on relationships for more information on eloquent relationships.

Upvotes: 1

Related Questions