2

Edit: to clarify, I want to get all the Nodes no matter if they have an Image. Further I don't want to return any records from Images_Nodes if there is no corresponding record in Images. This is a simplified version of a more complex query, so don't be cute thinking to tell me that my database isn't designed correctly.


I am using Laravel 5.5 and want to do a slightly more complicated query.

select
    n.Node_id, i.Image_id
from
    Nodes AS n
    left join Nodes_Images AS n_i
        join Images i ON n_i.Image_id = i.Image_id
    ON n.Node_id = n_i.Node_id

I thought that

DB::table('Nodes AS n')
    ->leftJoin('Nodes_Images AS n_i', function ($join) {
        $join->on('n.node_id', '=', 'n_i.node_id')
            ->join('images AS i', 'n_i.image_id', '=', 'i.image_id');
    })->select('n.node_id', 'i.image_id');

would produce it, but it returns

select
    [n].[node_id], [i].[image_id]
from
    [Nodes] as [n] 
    left join [Nodes_Images] as [n_i] 
    on [n].[node_id] = [n_i].[node_id]

and this

DB::table('Nodes AS n')
    ->leftJoin('Nodes_Images AS n_i', 'n.node_id', '=', 'n_i.node_id')
    ->join('images AS i', 'n_i.image_id', '=', 'i.image_id')
    ->select('n.node_id', 'i.image_id');

produces this, which does not nest the Images join inside the outer join

select
    [n].[node_id], [i].[image_id]
from
    [Nodes] as [n]
    left join [Nodes_Images] as [n_i] on [n].[node_id] = [n_i].[node_id] 
    inner join [images] as [i] on [n_i].[image_id] = [i].[image_id]
2
  • 1
    I believe this functionality does not exist and there doesn't seem to be a workaround other than writing raw SQL. I have created a pull request to hopefully rectify that. github.com/laravel/framework/pull/23059 Commented Feb 7, 2018 at 18:01
  • Great contribution! Commented Apr 14, 2020 at 8:39

1 Answer 1

1

This made it into Laravel 5.6.1

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.