Laravel 5.5 使用多对多关系时如何获取最新的N条记录?

Laravel 5.5 How to get latest N record When using Many to Many releationships?

我想从突发新闻类别中获取最新的十个记录。我在此处和网络上进行了搜索,但任何解决方案均无效..

我有 categoriespostspivot 个表格。

类别模型:

 public function posts(){

    return $this->belongsToMany('App\Post');
}

帖子模型

 public function categories(){

        return $this->belongsToMany('App\Category');
    }

控制器

  $breaking_news =  Category::where('id',6)->with('posts')->orderBy('id','desc')->take(2)->get();

  return view('frontend.home',compact('breaking_news'));

dd($breaking_news) 截图:https://screenshots.firefox.com/rK9hbBq4pIru1o1s/localhost

有什么建议吗?

您需要将 posts 限制为 N 而不是类别。有两种方法可以做到这一点:

 $breaking_news =  Category::where('id',6)->with('posts')->first()->posts->sortBy('id')->take(2); //$breaking_news will be a collection of posts

或者

 $breaking_news =  Post::whereHas('categories', function ($query) {
       $query->where("id", 6);
 })->orderBy('id','desc')->take(2)->get(); // Also a collection of posts but each post will have a ->categories collection as well.