Scope query in a many to many relationship

Deadly 提交于 2019-12-11 04:37:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!