我有两个一对多关系的模型。
class User extends ConfideUser {
public function shouts()
{
return $this->hasMany('Shout');
}
}
class Shout extends Eloquent {
public function users()
{
return $this->belongsTo('User');
}
}
这似乎工作良好。但是,我如何让它返回嵌套在呼喊对象中的用户对象呢?现在它只返回我所有的呼喊,但我没有在JSON中访问属于用户模型。
Route::get('api/shout', function() {
return Shout::with('users')->get();
});
这只返回这个JSON,对于每个呼喊没有用户对象:
[{"id":"1","user_id":"1","message":"A little test shout!","location":"K","created_at":"2013-05-23 19:51:44","updated_at":"2013-05-23 19:51:44"},{"id":"2","user_id":"1","message":"And here is an other shout that is a little bit longer...","location":"S","created_at":"2013-05-23 19:51:44","updated_at":"2013-05-23 19:51:44"}]
我在使用Laravel 5时有同样的问题。只是想补充一下,我通过在模型上使用Model::with("relationship")->get()
方法使其工作。
我明白了。
处理"belongsTo"关系时,方法需要命名为user()而不是users()。
是有意义的。
似乎有效
如果您使用:
protected $visible = ['user'];
不要忘记添加关系,以便在JSON中可见
可以在class Shout上使用protected $with = ['users'];
,而使用protected $with = ['shouts'];
。
和给出完整的命名空间模型名称
class Shout extends Eloquent {
protected $with = ['users'];
public function users()
{
return $this->belongsTo('AppUser');
}
}
和
class User extends ConfideUser {
protected $with = ['shouts'];
public function shouts()
{
return $this->hasMany('AppShout');
}
}
收到它
Route::get('api/shout', function() {
return Shout::all()->toJson;
});