如何使用 Sequel::Model 对两个表进行分页?
为了进行更改,我使用基于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您想要对标签和帖子的组合进行分页,您可能想要对两个关联数据集的并集进行分页:
但是,除非 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:
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.