我有两张桌子 - Categories
和Posts
。它们之间的关系是一对多的。即 - 一个类别有很多帖子。
我正在尝试使用最新的3个帖子获取所有Categories
的列表
我试过这个: -
$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();
但它似乎仅适用于第一类,后续类别为空。
答案 0 :(得分:1)
您可以尝试这样的事情:
$categories = Category::all()->each(function($category) {
$category->posts = $category->posts()
->addSelect(['name', 'excerpt', 'category_id'])
->latest()->take(3)->get();
});