我是laravel的新人。我需要在我的主页博客中为每个类别提取3个帖子,只显示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个最新帖子仅针对1个类别,并显示1个帖子为另一个。
答案 0 :(得分:1)
控制器的代码:
// 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
数组应该包含您需要的所有内容。