【发布时间】:2021-04-22 19:05:23
【问题描述】:
我有两个名为 posts 和 categories 的表。这两个表是一对多的关系,我用这样的模型写它们:
class Post extends Model
{
...
public function category()
{
return $this->belongsTo(Category::class, 'category_id', 'id');
}
...
}
class Category extends Model
{
...
public function posts()
{
return $this->hasMany(Post::class, 'category_id', 'id');
}
...
}
当我在控制器中使用$post = Post::find($id) 并检索一篇帖子并使用$post->category 获取此帖子的类别时,这很好用。但是如果我想一起检索所有帖子及其类别怎么办?
我的意思是,假设我在数据库中有 10 个帖子,并且我有 $posts = Post::get(); 来获取所有帖子。现在,我如何获得每个帖子的类别?
一种方法是循环!例如:
foreach($posts as $post) {
$post['category'] = $post->category;
}
return response()->json($posts);
是的!我想用 Json 回复,之前忘了说,抱歉。
有没有更好的方法来做到这一点?我搜索了一番,但我一无所获。如果有人回答我的问题,我将不胜感激。 :)
【问题讨论】: