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

nedo's avatar
Level 2

How to use JOIN query with LEFT() SQL function and query builder

Hi there. I'm having a problem with query builder using MSSQL and custom JOINs. It won't accept a SQL LEFT method as one of join conditions.

Here is the case:

I'm trying to construct a query with my Eloquent model which would look something like this.


SELECT 
[List].[LIST_ID]
[ListParam].[ADDR_ID],
[Addr].[ADMIN_CODE].
[Region].[NAME]
FROM List
INNER JOIN 
   [ListParam] ON [ListParam].[LIST_ID]=[List].[LIST_ID]
INNER JOIN
  [Addr] ON [ListParam].[ADDR_ID]=[Addr].[ADDR_ID]
INNER JOIN
  [Region] ON LEFT([Addr].[ADMIN_CODE],2)=[Region].[REGION_ID]

As you can see from above, the region ID consists of two first characters from the ADMIN_CODE field.

Don't ask me. I didn't create this database, just need to plug in...

So, when I use eloquent to construct a query using this:

->join("Region","LEFT(Addr.ADMIN_CODE,2)","=","Region.REGION_ID")

the query builder encapsulates the table.field_names in something like this

inner join [Region] on [LEFT(addr].[ADMIN_CODE,2)] = [Region].[REGION_ID]

basically destroying the whole query

The questions are

  1. Can I turn off field name encapsulation with [] somehow?
  2. How can I pass a raw statement to JOIN, I tried ->join with closure with no avail, I even tried to make a select raw with LEFT(field,)2 as helper_field, but it doesn't work well with join query
  3. Is there any other way to achieve what I want besides using DB::raw (which I really wouldn't like to do)

Thanks for your help

0 likes
2 replies
kossa's avatar

I think you can put directly you request using : DB::raw('All the request here')

nedo's avatar
Level 2

As I stated above I wanted to avoid DB::raw for the sake of security. I believe eloquent mistreats the LEFT(column,n) statement and this should be corrected in framework itself, or am I wrong?

Please or to participate in this conversation.