show last post from each category

前端 未结 3 1671
时光取名叫无心
时光取名叫无心 2020-12-11 10:30

I have two models Post and Category

// migration post

public function up()
{
    Schema::create(\'posts\', function (Blueprint $table) {
        $ta         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 11:07

    An Eloquent solution for loading categories with latest post is to create an additional hasOne() relationship in the Category model:

    public function latestPost()
    {
        return $this->hasOne(Post::class)->latest();
    }
    

    And then use eager loading:

    Category::with('latestPost')->get();
    

    This will generate just 2 queries to DB.

提交回复
热议问题