简体   繁体   中英

How to get latest n number of related model records in laravel

I have two tables - Categories and Posts . The relationship between them is one-to-many. ie - A category has many posts.

I am trying to get a list of all Categories with their latest 3 posts

I have tried this:-

$with = array('posts' => function($query) {
  $query->take(3);
  $query->orderBy('created_at', 'desc');
  $query->addSelect(array('name', 'excerpt','category_id'));
});

$categories = Category::with($with)->get();

But it seems to be working only for the first Category, the subsequent categories are empty.

You can try something like this:

$categories = Category::all()->each(function($category) {
    $category->posts = $category->posts()
                                ->addSelect(['name', 'excerpt', 'category_id'])
                                ->latest()->take(3)->get();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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