Laravel Eloquent:如何在通过 toArray/toJson 序列化时自动获取关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21589622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:59:10  来源:igfitidea点击:

Laravel Eloquent: How to automatically fetch relations when serializing through toArray/toJson

phplaravellaravel-4eloquent

提问by Ronni Egeriis Persson

I figures this works for automatically fetching userand replieswhen I am serializing my object to JSON, but is overriding toArrayreally the proper way of doing this?

我认为这适用于自动获取user以及replies当我将对象序列化为 JSON 时,但重写真toArray的是这样做的正确方法吗?

<?php

class Post extends Eloquent
{
    protected $table = 'posts';
    protected $fillable = array('parent_post_id', 'user_id', 'subject', 'body');

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function replies()
    {
        return $this->hasMany('Post', 'parent_post_id', 'id');
    }

    public function toArray()
    {
        $this->load('user', 'replies');
        return parent::toArray();
    }
}

回答by Jake

Instead of overriding toArray()to load user and replies, use $with.

而不是覆盖toArray()加载用户和回复,使用$with.

Here's an example:

下面是一个例子:

<?php

class Post extends Eloquent
{
    protected $table = 'posts';
    protected $fillable = array('parent_post_id', 'user_id', 'subject', 'body');

    protected $with = array('user', 'replies');


    public function user()
    {
        return $this->belongsTo('User');
    }

    public function replies()
    {
        return $this->hasMany('Post', 'parent_post_id', 'id');
    }

}

Also, you should be using toArray()in your controllers, not your models, like so:

此外,您应该toArray()在控制器中使用,而不是在模型中使用,如下所示:

Post::find($id)->toArray();

Hope this helps!

希望这可以帮助!

回答by PaybackTony

I must submit a new answer since I'm a SO pleb. A more proper way to accomplish this for those finding this on Google like I did would be to avoid using protected $withif you don't have to and instead move that with()call to your retrieval.

我必须提交一个新答案,因为我是一个普通人。对于像我一样在 Google 上发现此问题的人来说,完成此操作的更正确方法是避免使用(protected $with如果您不需要),而是将该with()调用移至您的检索。

<?php

class Post extends Eloquent
{
    protected $table = 'posts';
    protected $fillable = array('parent_post_id', 'user_id', 'subject', 'body');


    public function user()
    {
        return $this->belongsTo('User');
    }

    public function replies()
    {
        return $this->hasMany('Post', 'parent_post_id', 'id');
    }

}

And then you could modify the Post call to pre-load as needed:

然后您可以根据需要修改 Post 调用以进行预加载:

Post::with('user','replies')->find($id)->toArray();

This way, you won't be including un-needed data every time you grab a record, if you don't need it.

这样,如果不需要,每次抓取记录时都不会包含不需要的数据。