我试图在各种categories
中找到所有posts
。
我有Post
和Category
模型相关的belongsToMany()
如下:
发布
public function categories()
{
return $this->belongsToMany('AppCategory');
}
类别
public function posts()
{
return $this->belongsToMany('AppPost');
}
中间有category_post
的数据透视表,一切都与关系良好。
我遇到的问题如下。当user
查看post
时,我想显示相关的posts
,为此我想显示与post
属于同一categories
的posts
。
如果我执行以下操作:
$post = Post::where('slug',$slug)->first();
$relateds = $post->categories->first()->posts()->get();
我恢复了第一个category
的帖子,但该帖子有更多的相关categories
。我需要所有的帖子。
我尝试过:
$post = Post::where('slug',$slug)->first();
$relateds = $post->categories->get()->posts()->get();
$post = Post::where('slug',$slug)->first();
$relateds = $post->categories->all()->posts()->get();
还有几件类似的事情,但没有一件奏效。
请问正确的方法是什么?
谢谢。
您可以使用Post
生成器上的whereHas()
雄辩方法获取所有相关posts
。
$post = Post::where('slug',$slug)->first();
$category_ids = $post->categories->pluck('id')->all();
$related = Post::whereHas('categories', function($query) use ($category_ids) {
$query->whereIn('id', $category_ids);
})->get();
在这里,我们首先得到$post
.然后我们得到$post
的所有category
ID。
最后,我们得到所有posts
,其中有一个category
,并使用whereHas()
生成器方法(后跟whereIn()
查询方法(在$category_ids
变量中找到id
。
我希望这有所帮助。