问题
I created 2 models, "Post" and "Category". This is a many to many relationship, works great.
My tables are the following :
- alex_blog_posts : where posts are stored with columns like "title", "published" etc...
- alex_blog_categories : where categories are stored with columns like "title", "parent_id" etc...
- alex_blog_posts_categories : where the relation is stored between posts and categories with columns "post_id", "category_id"
Let's assume I want to filter all posts that are associated to a category with name : "Category 1"
public function scopeFilterCategory($query) {
$query->join(????); // My problem is to replace the ???
$query->where('title', '=', 'Category 1');
return $query;
}
I'm not familiar enought with october and laravel yet and I'm stuck here. Probably very simple for laravel expert but I need a concrete example of something working cause all things I tried failed :/
Thanks for your help
回答1:
laravel have the "whereHas":
https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence
On the post model you need the write this query:
$posts = Post::whereHas($relationName, function ($query) {
$query->where('title', =, 'Category 1');
})->get();
$relationName - should be the name of the function that define the relation in your model (etc: 'categories')
来源:https://stackoverflow.com/questions/46365305/scope-query-in-a-many-to-many-relationship