我有一个网站,我发布食谱 . 他们每个人都有一个类别,我想再显示2-3个与该帖子相同类别的帖子 . 我如何构建一个查询来显示它?我有一个Post Model和Category模型,它们之间有一个belongsToMany关系,它填充了一个数据透视表,我将这些类别绑定到一个帖子 .
这是我的BController中的函数,这是将数据传递给用户可以访问和查看的视图的函数 .
public function slug(Request $request, $slug)
{
if (Auth::check()) {
$fav = DB::table('post_user')->whereUserId(Auth::id())->pluck('post_id')->all();
}
/*get search query from slug page*/
$query=$request->get('q');
/*display the results of the search*/
if ($query) {
$posts = $query ? Post::search($query)
->orderBy('id','desc')
->paginate(7) : Post::all();
return view('home', compact('posts','fav'));
}
/*the $url veriable is for share buttons*/
else {
$url = $request->url();
$post = Post::where('slug', '=', $slug)->first();
return view('b.s', compact('post','url'));
}
}
this is my Post model:
public function categories(){
return $this->belongsToMany('App\Category');
}
this is in Category model:
public function posts(){
return $this->belongsToMany('App\Post');
}
The pivot table is like so:
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')
->on('posts')->onDelete('cascade');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')
->on('categories')->onDelete('cascade');
2 回答
您可以使用
whereHas
在相关表上添加约束,如下所示:Update
将
$related_posts
传递给您的视图并将其用作:可能的解决方案是包含一段代码以获得所需的类别 .
如果我正确理解您的模型,您可以有几个类别 . 所以,我们需要收集你帖子的所有类别,并且只保留id;我们必须排除当前对象的帖子ID :)
在您的情况下,您有一个数据透视表: