Updates:
June 2022 Laravel merged a PR (a year later from this topic) to Laravel 9, that add a new eloquent withWhereHas() -- doc
This ...
For further actions, you may consider blocking this person and/or reporting abuse
thanks for great article.
Now I know that with the
withWhereHas()I can load the relationship with specific condition.The macro should be
if not using lambda
Thanks. I solved the same problem with inner join which supposed to be more performance efficient.
Hello! 👋
JOIN could has better performance than WHERE EXISTS (with - eager loading), BUT:
The reason to use WITH, is for accessing models as related objects (with all their fields) instead of access a couple of fields specified in JOIN.
Great, would you please share your Macro?
Thanks for sharing. Worthy to note that laravel now has
withWhereHaseloquent method by defaultUnlike in your case, where withWhereHas is a scope.
of course that was helpful, instead of scoping it in each project !
I thought they'll never add it ...
Hi Othmane Nemli, thanks for your article.
I have one doubt though, I didn't understand why you use the whereHas query if you just specified the condition in the first query.
Don't you get the desired result only with the "with" query+condition?
Thanks in advance
Thanks for reading the article.
Well, using same condition in
with()andwhereHas()is to prevent N+1 and get only data that you asked for in thewhereHas(), so as I demonstrate the issue that we may face, the solution was to combinewith()andwhereHas()with same condition ..i use laravel 8 use \Illuminate\Database\Eloquent\Builder\Eloquent; not found
Thank you, I fixed the class name, you need to use
Illuminate\Database\Eloquent\Builderinsteadthank you very much.
thanks