2014-02-05 19 views
14

我这个人物的时候,我我的序列化对象JSON,但覆盖toArray真的这样做的正确方法适用于自动获取userreplies序列化时自动获取的关系?Laravel雄辩:如何通过指定者/的toJSON

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

回答

25
相反

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

} 

此外,你应该用你的控制器toArray(),不是你的车型,像这样:

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

希望这有助于!

+1

辉煌。我期望有一个更聪明的方法。 我正在利用Route :: model方法自动获取并将正确的模型传递给我的控制器。这是一个AJAX调用请求JSON,所以当我用我的控制器方法返回模型时,Laravel自动处理toJson调用:-) http://pastebin.com/5MMwiXS2 –

+2

这对我非常有用 - 谢谢!你碰巧知道'$ with'是否记录在任何地方?我无法在Laravel文档中找到它,但似乎确实有用。 – Vince

+0

它似乎只是[在源代码中](https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Model.php#L68)。 – bzeaman

2

我必须提交一个新的答案,因为我是一个SO祈祷者。对于像Google这样在Google上发现这个问题的用户,如果您不需要,可以避免使用protected $with,而是将with()调用移动到您的检索中。每次你抢了创纪录的时间,如果

Post::with('user','replies')->find($id)->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'); 
    } 

} 

然后你可以根据需要进行修改后调用预先加载你不需要它。

+0

这并不回答在序列化时自动获取的问题。 – bzeaman

+0

上面的答案,特别是'Post :: with('user','答复') - > find($ id) - > toArray();'将会加载一个包含关系的帖子,而不必按照要求覆盖toArray。此外,这只是对Jake发布的公认答案的修订,使其更加高效,因此您不必在每次实例化帖子时都加载用户和回复。 – PaybackTony