Querying relationship existence (Using Joins)
Querying relationship existence is a very powerful and convenient feature of Eloquent. However, it uses the where exists syntax which is not always the best and may not be the more performant choice, depending on how many records you have or the structure of your tables.
This packages implements the same functionality, but instead of using the where exists syntax, it uses joins. Below, you can see the methods this package implements and also the Laravel equivalent.
Please note that although the methods are similar, you will not always get the same results when using joins, depending on the context of your query. You should be aware of the differences between querying the data with where exists vs joins.
Laravel Native Methods
User::has('posts');
User::has('posts.comments');
User::has('posts', '>', 3);
User::whereHas('posts', fn ($query) => $query->where('posts.published', true));
User::whereHas('posts.comments', ['posts' => fn ($query) => $query->where('posts.published', true));
User::doesntHave('posts');
Package equivalent, but using joins
User::powerJoinHas('posts');
User::powerJoinHas('posts.comments');
User::powerJoinHas('posts.comments', '>', 3);
User::powerJoinWhereHas('posts', function ($join) {
$join->where('posts.published', true);
});
User::powerJoinDoesntHave('posts');
When using the powerJoinWhereHas method with relationships that involves more than 1 table (One to Many, Many to Many, etc.), use the array syntax to pass the callback:
User::powerJoinWhereHas('commentsThroughPosts', [
'comments' => fn ($query) => $query->where('body', 'a')
])->get());