我有一张桌子和一张桌子。每个Stories
包含多个Post
(Story
,Posts
)
我想要实现的是列出前10个按Story.hasMany(models.Post);
排序的故事。因此,第一个条目可能是最古老的故事,但有一个非常新的帖子。
我现在要做的是:
var options = {
limit: 10,
offset: 0,
include: [{
model: models.sequelize.model('Post'),
attributes: ['id', 'createdAt'],
required: true
}],
order: [
[models.sequelize.model('Post'), 'createdAt', 'DESC'],
['createdAt', 'DESC']
],
attributes: ['id', 'title', 'createdAt']
};
Story.findAll(options)...
这给了我这个SQL查询:
SELECT "Story".*, "Posts"."id" AS "Posts.id", "Posts"."createdAt" AS "Posts.createdAt"
FROM (SELECT "Story"."id", "Story"."title", "Story"."createdAt"
FROM "Stories" AS "Story"
WHERE ( SELECT "StoryId"
FROM "Posts" AS "Post"
WHERE ("Post"."StoryId" = "Story"."id") LIMIT 1 ) IS NOT NULL
ORDER BY "Story"."createdAt" DESC LIMIT 10) AS "Story"
INNER JOIN "Posts" AS "Posts" ON "Story"."id" = "Posts"."StoryId"
ORDER BY "Posts"."createdAt" DESC, "Story"."createdAt" DESC;
这里的问题是,如果第11个条目有一个非常新的帖子,它就不会显示在前10个列表中。
我怎样才能得到按
Post.belongsTo(models.Story);
排序的有限故事列表? 最佳答案
为什么要使用两个嵌套的子选择?这是无效的,可能会产生昂贵的嵌套循环,并且仍然不会返回您正在寻找的内容。
首先,您可以按照Posts的创建时间戳顺序交叉连接故事和帖子。但这可能会扫描整张桌子。
看一下这个演示:
http://www.slideshare.net/MarkusWinand/p2d2-pagination-done-the-postgresql-way
但我不知道,你怎么能把它带入你的模型中:-(