Dive into Laravel Eloquent: Exploring whereRelation
and its Practical Applications
This post explores Laravel's Eloquent ORM, focusing on the whereRelation
method and comparing it to the older whereHas
method. We'll examine its strengths and limitations, guiding you toward optimal usage.
Scenario: Retrieving users with completed orders. Before Laravel 8, whereHas
was the standard for querying related table columns. Laravel 8 introduced whereRelation
, offering a more concise syntax.
The improved syntax is undeniably cleaner!
Performance and Limitations: A common misconception is that whereRelation
outperforms whereHas
. However, analysis reveals that both generate identical SQL queries:
whereHas
Query:
<code class="language-sql">select * from `users` where exists ( select * from `orders` where `users`.`id` = `orders`.`created_by` and `status` = ? and `orders`.`deleted_at` is null ) and `users`.`deleted_at` is null</code>
whereRelation
Query:
<code class="language-sql">select * from `users` where exists ( select * from `orders` where `users`.`id` = `orders`.`created_by` and `status` = ? and `orders`.`deleted_at` is null ) and `users`.`deleted_at` is null</code>
The key difference lies in functionality. whereRelation
is limited to single conditions on the related table, while whereHas
supports multiple conditions within a single subquery. whereRelation
would create a separate subquery for each condition, making it inefficient for multiple criteria.
Choosing the right Eloquent method is crucial for code readability and efficiency. Consider the complexity of your query before selecting whereHas
or whereRelation
. Happy coding! ?
The above is the detailed content of Laravel Tip: whereHas or whereRelation?. For more information, please follow other related articles on the PHP Chinese website!