加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 19:47:44 所属栏目:大数据 来源:网络整理
导读:使用Laravel和雄辩的ORM,我想创建属于特定用户的所有帖子和相应注释的数组或对象(已登录的).结果将与Response :: eloquent()一起使用;返回 JSON. 基本上是伪代码: All Posts by user ::with('comments'). 要么 Posts by Auth::user()-id ::with('comments')
使用Laravel和雄辩的ORM,我想创建属于特定用户的所有帖子和相应注释的数组或对象(已登录的).结果将与Response :: eloquent()一起使用;返回 JSON.

基本上是伪代码:

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

要么

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

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

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

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

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

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

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

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

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:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读