Php 有说服力的关系

Php 有说服力的关系,php,laravel-5,orm,eloquent,Php,Laravel 5,Orm,Eloquent,我正在尝试查找各种类别中的所有帖子 我有Post和Category模型,它们与belongtomany()相关 详情如下: 发布 public function categories() { return $this->belongsToMany('App\Category'); } 类别 public function posts() { return $this->belongsToMany('App\Post'); } 中间有一个透视表category\u

我正在尝试查找各种
类别中的所有
帖子

我有
Post
Category
模型,它们与
belongtomany()相关
详情如下:

发布

public function categories()
{
    return $this->belongsToMany('App\Category');
}
类别

public function posts()
{
    return $this->belongsToMany('App\Post');
}
中间有一个透视表
category\u post
,所有这些关系都运行良好

我的问题如下。当
用户查看
帖子时
我想显示相关的
帖子
,为此我想显示与
帖子
属于相同
类别的
帖子

如果我这样做:

$post = Post::where('slug',$slug)->first();
$relateds = $post->categories->first()->posts()->get();
我恢复了第一个
类别的帖子
,但该帖子有更多关联的
类别
。我需要所有的帖子

我试过:

$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()
雄辩方法获取所有相关的
帖子

$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
的所有
类别
ID

最后,我们使用
whereHas()
builder方法(后面是
whereHas()
查询方法)获得所有
post
,其中它有一个
category
,id在
$category\u id
变量中


我希望这能有所帮助。

我的天啊,整个上午都在尝试。我还没有做采摘和使用($category_id)谢谢@thisiskelvin。这工作!这发生在我们最好的人身上。让我知道这是否有效。太好了!享受你的一天。