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

Ron*_*son 22 php laravel eloquent laravel-4

我认为这可以自动获取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();
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 46

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

这是一个例子:

<?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');
    }

}
Run Code Online (Sandbox Code Playgroud)

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

Post::find($id)->toArray();
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 这对我非常有帮助 - 谢谢!你碰巧知道`$ with`是否记录在任何地方?我在Laravel文档中找不到它,但它似乎确实可以解决问题. (2认同)

小智 5

由于实在太多,我必须提交新的答案。对于那些像我一样在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');
    }

}
Run Code Online (Sandbox Code Playgroud)

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

Post::with('user','replies')->find($id)->toArray();
Run Code Online (Sandbox Code Playgroud)

这样,您无需每次获取记录时都不需要包含不需要的数据。