如何使用 Sequel::Model 对两个表进行分页?

发布于 2024-12-13 02:07:30 字数 563 浏览 0 评论 0原文

为了进行更改,我使用基于 Ramaze 和 Sequel 的应用程序,而不是 Rails 应用程序。

我有一个模型 Tag,它通过连接表 :taggings:posts 多对多关联,并与 关联: external_posts 通过连接表 :external_post_taggings

我想将这两个关联收集在一起,并按日期字段对它们进行排序,该日期字段在每个表中称为 created_at

如果没有分页,我会这样做:

@combined = (@tag.posts + @tag.external_posts).sort_by(&:created_at).reverse

但是,我需要使用分页。如果只是 .posts 我会这样做:

@posts = @tag.posts.paginate(page, 10)

但我不知道如何跨两个表分页,如果可能的话。

For a change, I'm using a Ramaze, and therefore Sequel, based app instead of a Rails app.

I have a model Tag which is many-to-many associated with :posts via a join table :taggings, and with :external_posts via a join table :external_post_taggings.

I want to collect both of these associations together, and order them by a date field, which is called created_at in each table.

Without pagination, I would do:

@combined = (@tag.posts + @tag.external_posts).sort_by(&:created_at).reverse

However, I need to use pagination. If it was just .posts I would do:

@posts = @tag.posts.paginate(page, 10)

but I don't know how to paginate across two tables, if that's even possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

也只是曾经 2024-12-20 02:07:30

假设您想要对标签和帖子的组合进行分页,您可能想要对两个关联数据集的并集进行分页:

@tag.posts_dataset.
  union(@tag.external_posts_dataset).
  order(:created_at.desc).
  paginate(page, 10)

但是,除非 posts 和 external_posts 使用相同的模型类,否则这会出现问题。如果它们使用单​​独的模型类,您可能必须手动跟踪每个模型类的偏移量。基本上,对于每个页面,为两个关联选择接下来的 10 条记录(每条记录从适当的偏移量开始)。将2组10个合并成一个数组,按相反的created_at字段排序,取前10个结果。计算该 10 个组合/排序记录数组中帖子和外部帖子的数量,并相应更新帖子和外部帖子的偏移量以在下一页上使用。

例如,在第 1 页上,您可以对两者使用偏移量 0。如果在组合、排序并获取前 10 个帖子后,10 个帖子的数组中有 7 个帖子和 3 个外部帖子,则在第 2 页上,您将在第 2 页上开始帖子偏移量为 7,外部帖子偏移量为 3。

Assuming you want to paginate the combination of tags and posts, you probably want to paginate a union of the two association datasets:

@tag.posts_dataset.
  union(@tag.external_posts_dataset).
  order(:created_at.desc).
  paginate(page, 10)

However, this has issues unless posts and external_posts use the same model class. If they use separate model classes, you may have to keep track of the offsets manually for each. Basically, for each page, select the next 10 records for both associations (starting each at the appropriate offset). Combine the 2 groups of 10 into an array, sort it by the reversed created_at field, take the first 10 results. Count the number of posts and external posts in that array of 10 combined/sorted records, and update the offsets of posts and external posts accordingly for use on the next page.

For example, on page 1, you'd use offset 0 for both. If after combining, sorting, and taking the first 10, there are 7 posts and 3 external posts in the array of 10, on page 2 you would start the posts offset at 7 and the external posts offset at 3.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文