Below are the code examples of how to simplify querying a modal relationship that has a specific condition.
Laravel whereHas Method
Using "whereHas" function can allow you to query a model to check the condition of the relationship model and it works by passing the "relation" as the first param and closure as the second param to check the condition.
<?php Article::query() ->whereHas('comments', function ($query) { $query->where('article_id', 1); }) ->get();
Laravel whereHas Method with Anonymous Function
With PHP 7.4 you can make use of the arrow function to simplify the closure definition. This makes the closure into a one-liner and can be considered to be more straightforward.
<?php Article::query() ->whereHas('comments', fn ($query) => $query->where('article_id', 1)) ->get();
Laravel whereRelation Method
With the new "whereRelation" method now you can pass in the foreign key of the relationship into the second parameter and the "id" as the third parameter.
<?php Article::query() ->whereHas('comments', 'article_id', 1) ->get();
Leave a reply