微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php-Laravel:限制嵌套关系

下面是我必须提取所有带有相关主题和帖子的讨论的代码.我正在尝试将帖子数限制为1.执行此操作时,我希望每个线程中只有1个帖子,但是9个线程中没有帖子,而1个线程中有1个帖子.

App\discussion::with([
    'threads' => function ($query) => {
        // Correctly limits the number of threads to 10.
        $query->latest()->take(10);
    },
    'threads.posts' => function ($query) {
        // Limits all posts to 1, not each post to 1 for each thread.  
        $query->take(1);
    }
])->where(['slug' => 'something'])->firstOrFail();

上面的代码数据库中运行以下SQL查询.

select * from `discussions` where (`slug` = ?) and `discussions`.`deleted_at` is null limit 1

select * from `threads` where `threads`.`discussion_id` in (?) and `threads`.`deleted_at` is null order by `created_at` desc limit 10

select * from `posts` where `posts`.`thread_id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) and `posts`.`deleted_at` is null order by `created_at` desc limit 1

我可以看到第三个查询是导致问题的查询,因为它将所有帖子限制为1.

我希望看到以下内容;一次讨论,有10个主题,该主题中有1个帖子.

{
  "id": 1,
  "title": "discussion Title",
  ...
  "threads": [
    {
      "id": 1,
      "title": "Thread Title",
      ...
      "posts": [
        {
          "id": 1,
          "title": "Post Title",
          ...
        }
      ]
    }
    ...
  ]
}

有没有办法在Laravel框架中做到这一点,还是我必须运行原始查询?我宁愿尽可能坚持Eloquent ORM.

解决方法:

您需要做一些“调整”,因为Eloquent没有查询方法来限制关系中结果的数量.

首先在您的线程模型上创建此函数.

public function one_post()
{
    //OrderBy is optional
    return $this->hasOne(Post::class)->orderBy('id', 'asc');
}

现在您有了一个关系,该关系将仅返回一个帖子.您可以通过以下方式查询

    App\discussion::with([
        'threads' => function ($query) {
            // Correctly limits the number of threads to 10.
            $query
                ->latest()
                ->take(10)
                ->with('one_post');
        }
        ])->where(['slug' => 'something'])->firstOrFail();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐