5

我有两个具有一对多关系的模型。

class User extends ConfideUser {

    public function shouts()
    {
        return $this->hasMany('Shout');
    }

}

class Shout extends Eloquent {

    public function users()
    {
        return $this->belongsTo('User');
    }

}

这似乎工作正常。但是,我如何让它返回嵌套在喊对象中的用户对象?现在它只返回我所有的 Shouts,但我无法在 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"}]
4

4 回答 4

4

我在使用 Laravel 5 时遇到了同样的问题。只是想补充一点,我通过使用Model::with("relationship")->get()模型上的方法让它工作。

于 2015-09-24T17:39:31.370 回答
2

我想到了。

使用“belongsTo”关系时,该方法需要命名为 user() 而不是 users()。

说得通。

并且似乎有效。

于 2013-05-24T17:07:09.117 回答
1

您可以protected $with = ['users'];在 Class Shout 上使用并使用protected $with = ['shouts'];.

并给出完整的命名空间模型名称

class Shout extends Eloquent {

   protected $with = ['users'];

   public function users()
   {
    return $this->belongsTo('App\User');
   }
}

class User extends ConfideUser {

    protected $with = ['shouts'];

    public function shouts()
    {
        return $this->hasMany('App\Shout');
    }
}

接收它

Route::get('api/shout', function() {
    return Shout::all()->toJson;
});
于 2017-11-18T17:07:40.743 回答
1

如果您正在使用:

protected $visible = ['user'];

不要忘记添加关系,以便在 JSON 中可见

于 2015-08-18T07:37:36.420 回答