使用 Laravel 和 Eloquent 获取相关对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20199526/
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 08:41:59  来源:igfitidea点击:

Fetching related objects with Laravel and Eloquent

phplaravellaravel-4

提问by salgua

I created some models in Laravel extending the Eloquent class. In these models I added relations, like in this example:

我在 Laravel 中创建了一些扩展 Eloquent 类的模型。在这些模型中,我添加了关系,就像在这个例子中一样:

//in the User class
public function group()
{
    return $this->belongsTo('Group');
}

in this way I'm able to retrieve the group object for a specific user in this simply way:

通过这种方式,我能够以这种简单的方式检索特定用户的组对象:

User::find(1)->group

and this is nice. I need to fetch the entire table and display it in json format, so I do

这很好。我需要获取整个表并以json格式显示,所以我这样做

User::all()->toJson()

I obtain the whole table, but I have the "group_id" column instead of the group object. Is there a simple way to include related object in JSON? I know that I can loop in the collection and manually add the object, but I think that should be bad practice because I need to do a lot of query, when this problem can be solved using a single query with a join. Any idea?

我获得了整个表,但我有“group_id”列而不是组对象。有没有一种简单的方法可以在 JSON 中包含相关对象?我知道我可以在集合中循环并手动添加对象,但我认为这应该是不好的做法,因为我需要进行大量查询,而这个问题可以使用带有连接的单个查询来解决。任何的想法?

回答by Nathan Loding

I believe eager loading is what you're looking for: http://laravel.com/docs/eloquent#eager-loading

我相信急切加载是你正在寻找的:http: //laravel.com/docs/eloquent#eager-loading

User::with('group')->get()->toJson()

User::with('group')->get()->toJson()

Edit:fixing call to get()from all()

编辑:修复呼叫get()来自all()

回答by salgua

Soved!

索维!

User::with('group')->get()->toJson()