2
我有一個表Stories
和一個表Post
。每個Story
包含多個Posts
(Story.hasMany(models.Post);
,Post.belongsTo(models.Story);
)查找最後n個協會訂購的條目
我試圖實現是要列出前10個故事由Posts.createdAt
訂購。所以有可能第一個入口是最古老的故事,但有一個非常新的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名單中。
如何獲取Posts.createdAt
訂購的故事列表?
感謝SlideShare上我真的很喜歡省略的想法所抵消。 –