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

vrapan's avatar

Eloquent equivalent of inner join

Hi,

I got a one to one and a one to many relationship and I use with to pull the data which is fine but.... One of the relations is on well over 10000 rows, and SQL server complains that it can only handle 2100 parameters. That error made me realise that the With eloquent option creates a where clause that translates to this : where (id) in (foreign table ids) which exceeds 2100.

So does with only produce this kind of where and therefore I need to use the query builder as opposed to eloquent? If that is a case that is fine as I am quite fluent in SQL but just was wondering if there is a way to do it with eloquent.

0 likes
8 replies
JarekTkaczyk's avatar

@vrapan Yes, eloquent does it this way and no other.

You want query builder, no need for raw SQL, in order to do it. However, the question is, why would you want to pull all 10000 records at once?

vrapan's avatar

@JarekTkaczyk the end result of the query is around 150 odd rows but to get all the data I want I need to join a couple tables together. The rows linked between the tables are quite a few. An inner join would work a where in would be not so great.

Thanks for the reply though at least I will not be hunting down a way to do this that does not exist.

JarekTkaczyk's avatar

@vrapan Then I suppose you didn't want a with, but rather has/whereHas. However it still might not be the best in this case.

vrapan's avatar

just read up on those two and they are useful but I think in the end it is a bit more hassle than just query builder which is what I used. QB is a lot like SQL which I enjoy anyway!

claar's avatar

Eloquent objects can use all query builder methods such as join:

$result = User
    ::join('contacts', 'users.id', '=', 'contacts.user_id')
    ->join('orders', 'users.id', '=', 'orders.user_id')
    ->select('users.id', 'contacts.phone', 'orders.price')
    ->getQuery() // Optional: downgrade to non-eloquent builder so we don't build invalid User objects.
    ->get();

I do this whenever ->with would create hundreds of related objects I don't care about -- huge performance difference.

10 likes
hpmhpm's avatar

@claar it's exactly what many people are searching for, Thanks and another one for using getQuery()!

1 like

Please or to participate in this conversation.