简体   繁体   English

获取Laravel中每个类别的帖子

[英]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个相关模型 ,您需要更复杂的解决方案-看看:

  1. n per parent 每个父母n个

  2. 1 per parent 每个父母1个

  1. Maybe you can get use $categories = Category::all() to get all categories first. 也许您可以使用$ categories = Category :: all()来首先获取所有类别。
  2. foreach $categories and get the latest four posts by $posts=$category->posts foreach $ categories并通过$ posts = $ category-> posts获得最新的四个帖子
  3. merge the posts array into one array 将posts数组合并为一个数组
  4. pass categories and posts to the view. 将类别和帖子传递给视图。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM