一对多然后使用 Laravel Eloquent ORM 急切加载数组

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

One-to-many then eager load an array with Laravel Eloquent ORM

phpormlaraveleloquent

提问by drew schmaltz

With Laravel and the eloquent ORM, I want to create an array or object of all posts and corresponding comments that belong to a specific user (the logged in one). The result will then be used with Response::eloquent(); to return JSON.

使用 Laravel 和 eloquent ORM,我想创建属于特定用户(已登录用户)的所有帖子和相应评论的数组或对象。结果将用于 Response::eloquent(); 返回 JSON。

Basically in pseudo-code:

基本上是伪代码:

All Posts by user ::with('comments').

or

或者

Posts by Auth::user()->id ::with('comments').

I have my database setup per the usual with a user's table, comments table and posts table. The comments table has a post_id and the posts table has a user_id.

我按照通常的方式使用用户表、评论表和帖子表设置了我的数据库。评论表有一个 post_id,posts 表有一个 user_id。

The long way of doing this without Laravel would be something like:

在没有 Laravel 的情况下这样做的漫长道路将是这样的:

SELECT * FROM posts WHERE user_id = 'user_id'
foreach($result as $post) {
    SELECT * FROM comments WHERE posts_id =  $post->id
    foreach($query as $comment) {
        $result[$i]->comments[$n] = $comment
    }
}

But I want to accomplish it with Laravel's Eloquent ORM.

但我想用 Laravel 的 Eloquent ORM 来完成它。

回答by Cthos

It looks like you don't even need a nested eager load, you just need to modify the query that with returns, so:

看起来您甚至不需要嵌套的急切加载,您只需要修改带有返回的查询,因此:

$posts = Post::with('comments')->where('user_id', '=', 1)->get();

You can daisy chain most of the methods in the Eloquent system, generally they're just returning a Fluent query object.

您可以菊花链式链接 Eloquent 系统中的大多数方法,通常它们只是返回一个 Fluent 查询对象。

(I haven't tested it but I'm fairly certain that'll work. Also, you can't do it on ::all() because that calls ->get() for you. You have to dig in the source code to find this, I don't think the Eloquent documentation mentions that's what it's doing.)

(我还没有测试过,但我很确定它会起作用。另外,你不能在 ::all() 上这样做,因为它会为你调用 ->get()。你必须挖掘源代码找到这个的代码,我认为 Eloquent 文档没有提到它在做什么。)

Also the Eager Loading Documentationcovers nested eager loading, so you could load all users, with their posts, with the comments:

另外,预先加载文档盖嵌套预先加载,所以你可以加载所有的用户,用自己的岗位,用评论:

You may even eager load nested relationships. For example, let's assume our Author model has a "contacts" relationship. We can eager load both of the relationships from our Book model like so:

您甚至可以急切加载嵌套关系。例如,假设我们的 Author 模型有一个“联系人”关系。我们可以像这样从我们的 Book 模型中预先加载这两种关系:

$books = Book::with(array('author', 'author.contacts'))->get();