Orm Laravel口若悬河,返回JSON时使用;“属于”;对象
我有两个一对多关系的模型Orm Laravel口若悬河,返回JSON时使用;“属于”;对象,orm,laravel,laravel-4,eloquent,Orm,Laravel,Laravel 4,Eloquent,我有两个一对多关系的模型 class User extends ConfideUser { public function shouts() { return $this->hasMany('Shout'); } } class Shout extends Eloquent { public function users() { return $this->belongsTo('User'); }
class User extends ConfideUser {
public function shouts()
{
return $this->hasMany('Shout');
}
}
class Shout extends Eloquent {
public function users()
{
return $this->belongsTo('User');
}
}
这似乎很管用。
但是,如何让它返回嵌套在shout对象中的users对象呢?
现在,它只返回我所有的叫喊,但我在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"}]
我想出来了
使用“belongsTo”关系时,该方法需要命名为user()而不是users()
有道理
并且似乎有效。如果您正在使用:
protected $visible = ['user'];
别忘了添加关系,以便在JSON中可见,我在使用Laravel 5时也遇到了同样的问题。只是想补充一点,我是通过在模型上使用
Model::with(“relationship”)->get()
方法实现的在类中使用protected$with=['shouts']代码>
并给出完整的名称空间模型名
class Shout extends Eloquent {
protected $with = ['users'];
public function users()
{
return $this->belongsTo('App\User');
}
}
及
收到
Route::get('api/shout', function() {
return Shout::all()->toJson;
});
目前我还在Laravel中构建一个API,我强烈建议查看和嵌套资源。这里还有一个关于这个主题的不错的教程:
Route::get('api/shout', function() {
return Shout::all()->toJson;
});