[英]Get posts foreach categories in Laravel
I am using Laravel 4 我正在使用Laravel 4
Here is my Controller: 这是我的控制器:
public function getArticles()
{
$categories = Category::with(['posts' => function($query){
$query->orderBy('updated_at', 'DESC')->take(4)->get();
}])->get();
return View::make('articles', compact('categories'));
}
Here is my View: 这是我的观点:
@foreach($categories as $category)
<h1>{{$category->title}}</h1>
<ul>
@foreach($category->posts as $post)
<li>
<a href="{{ $post->url() }}">{{ $post->title }}</a>
</li>
@endforeach
</ul>
@endforeach
My Category Model: 我的类别模型:
class Category extends Basemodel {
public function posts(){
return $this->hasMany('Post');
}
}
And my Post Model: 我的帖子模型:
class Post extends Basemodel {
public function category(){
return $this->belongsTo('Category');
}
}
So it displays correctly my 6 categories (titles), but it only displays 4 posts total, I would like to display the 4 latest posts for each category (24 posts total). 因此它可以正确显示我的6个类别(标题),但仅显示4个帖子,我想针对每个类别显示4个最新帖子(总共24个帖子)。 I tried many things, and searched online but couldn't find a way around it.
我尝试了很多事情,并在网上搜索,但找不到解决方法。
You can't do that using limit
in the eager loading closure, because, as you noticed, it limits the other query, that fetches all the posts. 您不能在急切的加载闭包中使用
limit
来做到这一点,因为,正如您所注意到的,它限制了另一个查询,即获取所有帖子。
You can easily get single related model with eager loading for hasMany
with a helper relation: 您可以轻松地为具有渴望关系的
hasMany
加载单个相关模型并进行以下操作:
public function latestPost()
{
return $this->hasOne('Post')->latest();
}
but for n related models per each parent , you need a bit more complex solution - take a look at: 但是对于每个父级的n个相关模型 ,您需要更复杂的解决方案-看看:
Cheers. 干杯。
I hope you can write the correct foreach. 我希望您可以编写正确的foreach。 And when retrieving the posts, use $category->posts instead of $category->posts(), which results in an error.
并且在检索帖子时,请使用$ category-> posts而不是$ category-> posts(),这将导致错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.