【问题标题】:is there a way to get all related data in laravel connection?有没有办法在 laravel 连接中获取所有相关数据?
【发布时间】:2021-04-22 19:05:23
【问题描述】:

我有两个名为 postscategories 的表。这两个表是一对多的关系,我用这样的模型写它们:

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 回复,之前忘了说,抱歉。

有没有更好的方法来做到这一点?我搜索了一番,但我一无所获。如果有人回答我的问题,我将不胜感激。 :)

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    使用 json 在每个帖子模型中包含类别的最简单方法是使用 with() 简单地包含它,它会自动转换它。

    return Post::with('category')->get();
    

    Laravel 中,您不必在response->json(); 中包装模型或集合,它会自动执行此操作。

    【讨论】:

    • 我不确定这是否是您想要的,但其他评论我希望您想要以下 json 结构。 [{"name": "post 1", "category": {"name": "cat 1"}}]
    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多