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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16739950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:48:51  来源:igfitidea点击:

Laravel Eloquent, return JSON with "belongsTo" object?

ormlaravellaravel-4eloquent

提问by Emin

I have two models with a one-to-many relationship.

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

class User extends ConfideUser {

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

}

class Shout extends Eloquent {

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

}

This seem to work fine. BUT, How do I get this to return the users object nested in the shout objects? Right now it only returns all my Shouts, but I have no access in the JSON to the belonging user model.

这似乎工作正常。但是,如何让这个返回嵌套在呼喊对象中的用户对象?现在它只返回我所有的 Shouts,但我无法在 JSON 中访问所属用户模型。

Route::get('api/shout', function() {
    return Shout::with('users')->get();
});

This just returns this JSON, with no user object for every shout:

这只是返回这个 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"}]

采纳答案by Emin

I figured it out.

我想到了。

The method needs to be named user() not users() when working with "belongsTo" relationship.

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

Makes sense.

说得通。

And seems to work.

并且似乎有效。

回答by Emin

I was having the same trouble using Laravel 5. Just wanted to add that I got it to work by using the Model::with("relationship")->get()method on the model.

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

回答by Mantas D

If you are using:

如果您正在使用:

protected $visible = ['user'];

Don't forget to add there relationship, to be visible in JSON

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

回答by Chando

u can use protected $with = ['users'];on Class Shout and use protected $with = ['shouts'];.

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

and Give Full namespace model name

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

class Shout extends Eloquent {

   protected $with = ['users'];

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

and

class User extends ConfideUser {

    protected $with = ['shouts'];

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

Receive It

收到

Route::get('api/shout', function() {
    return Shout::all()->toJson;
});