【发布时间】:2014-09-07 09:21:48
【问题描述】:
我有这个模型给作者:
<?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 形式返回所有内容,有没有办法在不指定要获取哪些属性的情况下获取模型及其所有属性??
【问题讨论】:
-
你试过
$author = json_encode(Author::with('albums')->where('name','=','Chester Bennington')->first()); -
刚刚回答了我的问题,谢谢。