如何在laravel中获取最新的n个相关模型记录

I have two tables - Categories and Posts. The relationship between them is one-to-many. i.e - 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();
});