我有一个网站,我在那里发布食谱。他们每个人都有一个类别,我想再显示 2-3 个与该帖子相同类别的帖子。
我怎样才能建立一个查询来显示它?我有一个 Post Model 和 Category 模型,它在两者之间有一个belongsToMany 关系,它填充了一个数据透视表,我将这些类别绑定(bind)到一个帖子。

这是我的 BController 中的函数,这是将数据传递给用户可以访问和查看的 View 的函数。

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

最佳答案

您可以使用 whereHas 在相关表上添加约束,如下所示:

// 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 传递给您的 View 并将其用作:
@foreach ($related_posts as $related_post)
    <li>{{ related_post->title }}</li>
@endforeach

关于php - 根据laravel中的相同类别制作 'Related To'部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41321454/

10-08 22:14
查看更多