php – 一对多,然后渴望加载一个数组与Laravel雄辩ORM

前端之家收集整理的这篇文章主要介绍了php – 一对多,然后渴望加载一个数组与Laravel雄辩ORM前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用Laravel和雄辩的ORM,我想创建属于特定用户的所有帖子和相应注释的数组或对象(已登录的).结果将与Response :: eloquent()一起使用;返回 JSON.

基本上是伪代码:@H_502_2@

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

要么@H_502_2@

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

我根据用户的表,注释表和帖子表,通常使用我的数据库设置.注释表具有一个post_id,并且posts表具有一个user_id.@H_502_2@

没有Laravel的漫长的做法就是这样:@H_502_2@

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
    }
}

但是我想用Laravel的雄辩的ORM来完成它.@H_502_2@

看起来你甚至不需要嵌套的加载,你只需要修改与返回的查询,所以:
$posts = Post::with('comments')->where('user_id','=',1)->get();

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

(我没有测试过,但我相当肯定会工作,而且,你不能在:: all()上执行它,因为调用 – > get(),你必须挖掘源代码找到这个,我不认为这个雄辩的文档提到这是正在做的.)@H_502_2@

另外Eager Loading Documentation还包含了嵌套的加载,所以你可以加载所有的用户,他们的帖子和评论:@H_502_2@

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:@H_502_2@

$books = Book::with(array('author','author.contacts'))->get();
原文链接:https://www.f2er.com/laravel/131266.html

猜你在找的Laravel相关文章