Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

phpMick's avatar
Level 15

LEFT JOIN Query Builder and SQL

Hi,

I'm struck on the last step of getting a query to work.

I have an instance of query builder, which I need to LEFT JOIN with an SQL SELECT. It's pretty complex, so I'm trying to avoid pasting it all in here. I will try and simplify.

I have something like:

1, $SQL = 'SELECT * FROM things' (greatly simplified)

2, $query (Query Builder instance)

and I want to end up with something like:

SELECT * FROM ($SQL) AS cal LEFT JOIN ($query) AS x

ON x.datekey = cal.all_days

Any idea how to do this? I think it's probably using: leftJoinSub()

0 likes
2 replies
phpMick's avatar
Level 15

@SilenceBringer

Yes, that's it.

I just got it working like this:

        $builder->fromSub($SQL, 'cal');

        $things =  $builder->leftJoinSub($query, 'x', function ($join) {
            $join->on('x.datekey', '=', 'cal.all_days');
        })->orderBy('cal.all_days')
            ->get();

Please or to participate in this conversation.