Laravel Eloquent,返回带有“belongsTo”对象的 JSON?

Posted

技术标签:

【中文标题】Laravel Eloquent,返回带有“belongsTo”对象的 JSON?【英文标题】:Laravel Eloquent, return JSON with "belongsTo" object? 【发布时间】:2013-05-20 08:22:33 【问题描述】:

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

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"]

【问题讨论】:

我现在也在 Laravel 中构建一个 API,我强烈建议查看 resourceful controllers 和嵌套资源。这里也是一个很好的主题教程:tutsplus.com/lesson/nested-resources 【参考方案1】:

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

【讨论】:

【参考方案2】:

我想通了。

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

有道理。

而且似乎有效。

【讨论】:

【参考方案3】:

如果您正在使用:

protected $visible = ['user'];

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

【讨论】:

【参考方案4】:

你可以在 Class Shout 中使用protected $with = ['users']; 并使用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;
);

【讨论】:

以上是关于Laravel Eloquent,返回带有“belongsTo”对象的 JSON?的主要内容,如果未能解决你的问题,请参考以下文章