如何在 laravel 中检索与当前 post 类别相同的 post?
how to retrive posts where their category is same with current post in laravel?
我有 post 和类别多对多关系,其中 post 和类别模型定义正确,我有枢轴 table 到但没有枢轴 table 的模型。
当我得到一个 post 时,我有 post 个类别,$post-> 类别。
我想列出当前 post 类别的所有 post,例如,如果当前 post 的类别为 A 和 B,我想检索所有 post 的类别A和B。
laravel Elequent 为此目的最好和最简单的方法是什么?
这里是我的模型,如果有帮助的话
class Post extends Model
{
public function categories(){
return $this->belongsToMany(Category::class);
}
}
class Category extends Model
{
public function posts(){
return $this->belongsToMany(Posts::class);
}
}
public function singlePost(Post $post){
$postsWithSameCategory = ???
return view('home.post',compact('post'));
}
如果你想要相同类别的帖子
根据你的例子;将返回类别 A、B、A/B、A/B/C 的帖子
public function singlePost(Post $post){
$postsWithSameCategory = Post::whereHas('categories', function($query) use ($post) {
$query->whereIn('id', $post->categories->pluck('id'));
})->get();
return view('home.post',compact('post', 'postsWithSameCategory'));
}
如果您想要具有完全相同类别的帖子
根据你的例子;只会返回类别为 A/B 的帖子
public function singlePost(Post $post){
$postsWithSameCategory = Post::whereHas('categories', function($query) use ($post) {
$query->whereIn('id', $post->categories->pluck('id'));
}, '=', $post->categories->count())->get();
return view('home.post',compact('post', 'postsWithSameCategory'));
}
要同时回答您的评论,您可以定义一个 scope 您的 Post
模型
public function scopeWhereIsRelatedWithPost($query, $post)
{
return $query->whereHas(/** ... **/);
}
$posts = Post::whereIsRelatedWithPost($post)->get();
我有 post 和类别多对多关系,其中 post 和类别模型定义正确,我有枢轴 table 到但没有枢轴 table 的模型。
当我得到一个 post 时,我有 post 个类别,$post-> 类别。 我想列出当前 post 类别的所有 post,例如,如果当前 post 的类别为 A 和 B,我想检索所有 post 的类别A和B。 laravel Elequent 为此目的最好和最简单的方法是什么?
这里是我的模型,如果有帮助的话
class Post extends Model
{
public function categories(){
return $this->belongsToMany(Category::class);
}
}
class Category extends Model
{
public function posts(){
return $this->belongsToMany(Posts::class);
}
}
public function singlePost(Post $post){
$postsWithSameCategory = ???
return view('home.post',compact('post'));
}
如果你想要相同类别的帖子
根据你的例子;将返回类别 A、B、A/B、A/B/C 的帖子
public function singlePost(Post $post){
$postsWithSameCategory = Post::whereHas('categories', function($query) use ($post) {
$query->whereIn('id', $post->categories->pluck('id'));
})->get();
return view('home.post',compact('post', 'postsWithSameCategory'));
}
如果您想要具有完全相同类别的帖子
根据你的例子;只会返回类别为 A/B 的帖子
public function singlePost(Post $post){
$postsWithSameCategory = Post::whereHas('categories', function($query) use ($post) {
$query->whereIn('id', $post->categories->pluck('id'));
}, '=', $post->categories->count())->get();
return view('home.post',compact('post', 'postsWithSameCategory'));
}
要同时回答您的评论,您可以定义一个 scope 您的 Post
模型
public function scopeWhereIsRelatedWithPost($query, $post)
{
return $query->whereHas(/** ... **/);
}
$posts = Post::whereIsRelatedWithPost($post)->get();