WhereHas in Laravel, to apply where conditions on relationships
Let's talk about the relationship between categories here. Remember that, for the book, we have the post, and with the post we get the category, as we have here:
class Book extends Model
{
***
public function post()
{
return $this->belongsTo(Post::class);
}
}
class Post extends TaggableModel
{
***
public function category()
{
return $this->belongsTo(Category::class);
//->select('id', 'title', 'slug');
}
}
That is, we don't have it as directly as we did with the post, where we could query the category very easily, because we already had it there. Maybe not the relationship directly, but at least the category_id was present.
If we check here, when we run the query, we ask directly about the category, that is, a field that is already part of the post entity. But things change here.
Relationship through the Post
We want to access the category not from a direct field, but from a relationship, which in this case is the post. It's that simple.
Therefore, the query method changes, and we have to use, in short, whereHas instead of where.
What is whereHas?
In short, the has (which I believe is the first time I've used it in a course) is the way to query relationships. It's that simple.
In short, we can't query relationships using a where statement. Although there's one small caveat: if you were using a join statement, you could perfectly well use where, which would be, so to speak, the traditional way of doing things.
But in this case, we're working with with, and therefore, we can't do it that way:
Book::with(['post', 'post.category'])
->when($this->category_id, function (Builder $query, $category_id) {
$query->whereHas('post', function ($q) use ($category_id) {
$q->where('category_id', $category_id);
});
})
Summary: Why do we use whereHas?
In short, whereHas is the mechanism we have for creating a where condition on a relationship.
Remember that: that's what we use whereHas for.
For everything else, there's Mastercard... sorry, there's Eloquent.
I agree to receive announcements of interest about this Blog.
I'll show you how whereHas works, in which we get the category reference from a book: Book - Post - Category
- Andrés Cruz