【问题标题】:Laravel Eloquent, return JSON with "belongsTo" object?Laravel Eloquent,返回带有“belongsTo”对象的 JSON?
【发布时间】: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"}]

【问题讨论】:

标签: orm laravel laravel-4 eloquent


【解决方案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;
        });
        

        【讨论】:

          猜你喜欢
          • 2020-07-04
          • 1970-01-01
          • 2021-06-03
          • 1970-01-01
          • 2022-01-07
          • 1970-01-01
          • 1970-01-01
          • 2014-12-11
          • 1970-01-01
          相关资源
          最近更新 更多