2014-02-05 22 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