根据 laravel 中的相同类别创建 'Related To' 部分

Make 'Related To' section based on same Category in laravel

我有一个网站,上面有 post 食谱。他们每个人都有一个类别,我想再显示 2-3 个与 post 具有相同类别的 post。 我怎样才能建立一个查询来显示它?我有一个 Post 模型和类别模型,两者之间有 belongsToMany 关系,它填充了一个枢轴 table,我将这些类别绑定到 post.

这是我的 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'));

        }
    }

这是我的Post模型:

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

这是在类别模型中:

public function posts(){
    return $this->belongsToMany('App\Post');
}

支点table是这样的:

            $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');

可能的解决方案是包含一段代码来获取所需的类别。

如果我正确理解你的模型,你可以有几个类别。因此,我们需要获取您 post 的所有类别,并只保留 id ;我们必须排除当前对象的 Post ID :)

$post = Post::where('slug', '=', $slug)->first();

// get Category IDs. There are others ways to do it.
$categoriesId = [];
foreach( $post->categories as $category ) {
  $categoriesId[] = $cateogyr->id;
}

// get similar posts
$others = Post::
     whereIn('categories', $categoriesId)
   ->where('id', '!=', $post->id)
   ->take(3)
   ->get();

在你的例子中,你有一个支点 table:

$others = Post::
   with(array('YourPivot' => function($query) use($categoriesId)
     {
       whereIn('categories', $categoriesId)
     })
   ->where('id', '!=', $post->id)
   ->take(3)
   ->get();

您可以使用 whereHas 对相关 table 添加约束,如:

// get the post usnig slug
$post = Post::where('slug', '=', $slug)->first();

// get the related categories id of the $post
$related_category_ids = $post->categories()->pluck('categories.id');

// get the related post of the categories $related_category_ids
$related_posts = Post::whereHas('categories', function ($q) use($related_category_ids) {
        $q->whereIn('category_id', $related_category_ids)
    })
    ->where('id', '<>', $post->id)
    ->take(3)
    ->get();

更新

$related_posts 传递到您的视图并将其用作:

@foreach ($related_posts as $related_post)
    <li>{{ related_post->title }}</li>
@endforeach