Laravel 4 Почта и категории

Я новичок в 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

Решение

Код для вашего контроллера:

// 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 Массив должен иметь все необходимое.

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector