Skip to content
Advertisement

Can i use where condtiton after calling relation with @with method?

This code:

JavaScript

Return output like this:

JavaScript

What can I do to return an empty array of users? I tried to do like this:

JavaScript

But got an error:

JavaScript

Advertisement

Answer

With the syntax you tried, the answer is “No”, as ->with() doesn’t perform any kind of join logic; so posts tables is not available there.

If you want to filter the User records returned based on a condition of a relationship, you need to use one of has() or whereHas() method. In your case, since you’re looking for votes > 100, with votes being a column, you need to use whereHas():

JavaScript

This will limit the User record being returned to those that have 100 votes or more.

Additionally, you can use both whereHas() and with() with the same function to Filter and Eager Load the relationship (preventing extra queries from being run later). Syntax for that would be:

JavaScript

Complete documentation is available here:

https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement