简体   繁体   English

然后用Laravel Eloquent ORM加载一对多的数组

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

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). 使用Laravel和雄辩的ORM,我想创建属于特定用户(登录的用户)的所有帖子和相应评论的数组或对象。 The result will then be used with Response::eloquent(); 然后结果将与Response :: eloquent()一起使用; to return JSON. 返回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. comments表有一个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来实现它。

It looks like you don't even need a nested eager load, you just need to modify the query that with returns, so: 看起来你甚至不需要嵌套的eager load,你只需要修改带有return的查询,所以:

$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 Documentation covers nested eager loading, so you could load all users, with their posts, with the comments: 此外, Eager Loading文档还包含嵌套的预先加载,因此您可以使用其评论加载所有用户及其评论:

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: 我们可以从我们的Book模型中急切加载这两种关系,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM