Laravel 4 Post 和类别

Laravel 4 Post and categories

我是 laravel 的新人。我需要在我的主页博客中为每个类别获取 3 posts,并且只显示 4 个类别。

我在我的 HomeController 中做

  $categories = Category::with(['posts' => function($query){
      $query->orderBy('published_at', 'DESC')->take(3)->get();
  }])->take(4)->get();

在我的模型中

//post models
     public function category(){
    return $this->belongsToMany('Category', 'post_categories', 'post_id', 'category_id');
    }

在我的类别模型中

    public function posts(){
       return $this->hasMany('Post');
   }

但是当我进入我的视图时,它只显示 3 个最新的 post 仅适用于 1 个类别,并显示 1 个 post 用于另一个类别。

您的控制器代码:

// declare a variable and an array
$catid = null;
$posts = [];

// get four categories
$categories = Category::take(4)->get();

foreach($categories as $category){
  //foreach of the four categories, get the category id
  $catid = $category->category_id;

  //add three posts of each of those categories to the $posts array
  $posts[] = Category::where('category_id', $catid)->take(3)->get();

}

您的 $posts 数组应该有您需要的一切。