显示每个类别的最新帖子 [英] show last post from each category

查看:62
本文介绍了显示每个类别的最新帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型Post和Category

I have two models Post and Category

//迁移后的帖子

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('body');
        $table->string('image');
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories');
        $table->timestamps();
    });
}

//迁移类别

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

如何仅显示首页中每个类别的最新帖子?

How can I display only the last post from each category in home page?

推荐答案

Hiren很近,但是您需要从类别中退出,因为您的postcategory

Hiren was close, but you need to go from the category since your post is owned by the category

$category->posts()->latest()->first();

或者,您可以向后工作:

Alternatively you could work backwards:

$post = Post::latest()->whereHas('category', function($q) use($category_id) {
    return $q->where('id', $category_id);
})->first();

为此,您需要定义模型关系:

For this to work you'll need to define your model relationships:

类别模型需要此功能:

public function posts() 
{
    return $this->hasMany(App\Post::class);
}

Post Model需要此功能:

Post Model needs this function:

public function category()
{
    return $this->belongsTo(App\Category::class);
}

要回复Alexey Mezenin,我们可以将回调传递给with(),以定义要为每个类别插入的帖子,并执行正确的eager load.

To respond to Alexey Mezenin, we can just pass a callback to with() to define which posts we want to pull in for each category, performing the correct eager load.

Category::with(['posts' => function($q) {
    return $q->latest()->first();
})->get(); 

这篇关于显示每个类别的最新帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆