2014-07-16 27 views
0

我有這個模型作者:獲得所有屬性與一個型號爲JSON

<?php 


class Author extends Eloquent {  

    public function albums() 
    { 
    return $this->belongsToMany('Album')->withPivot('city'); 
    } 

} 

而且這款型號爲專輯:

<?php 


class Album extends Eloquent { 

    public function artist() 
    { 
    return $this->belongsTo('Artist'); 
    } 

    public function authors() 
    { 
    return $this->belongsToMany('Author')->withPivot('city'); 
    } 

} 

爲了得到一個模式,我可以很容易地做到這一點:

$author = Author::where('name','=','Chester Bennington')->first()->toJson();

,它會返回這樣的事情(如JSON):

{"id":3,"name":"Chester Bennington","created_at":"2014-06-29 16:10:21","updated_at":"2014-06-29 16:10:21"}

看到,它不會返回與之相關的相冊。要獲取相冊我將不得不這樣做:$author->albums->toJson()

由於我正在做一個API,它將所有返回爲JSON,有沒有一種方法來獲取模型和所有的屬性,而不指定哪些獲得?

+0

你試過'$作者= json_encode(作者::用( '相冊') - >在哪裏( '名' ,'=','Chester Bennington') - > first());' – user3158900

+0

這只是回答了我的問題,謝謝。 – Mathius17

回答

1

如果eager load the relationships你想,它會被包含在您的JSON:

Author::with('albums')->where('name', 'Chester Bennington')->first()->toJson(); 
相關問題