【发布时间】:2015-03-26 07:19:28
【问题描述】:
在限制结果和包含关联模型时,我遇到了 Sequelize 问题。
以下产生正确的结果,限制为 10 并正确排序。
Visit.findAll({
limit: 10,
order: 'updatedAt DESC',
}).success(function(visits) {
res.jsonp(visits);
}).failure(function(err) {
res.jsonp(err);
})
SQL
SELECT * FROM `Visits` ORDER BY updatedAt DESC LIMIT 10;
但是,当我添加一个关联时,它突然限制了子查询,因此由于结果集有限,排序永远不会发生。
Visit.findAll({
limit: 10,
order: 'updatedAt DESC',
include: [
{ model: Account, required: true }
]
}).success(function(visits) {
res.jsonp(visits);
}).failure(function(err) {
res.jsonp(err);
})
SQL
SELECT
`Visits`.*
FROM
(SELECT
`Visits`.*, `Account`.`id` AS `Account.id`, `Account`.`email` AS `Account.email`, `Account`.`password` AS `Account.password`, `Account`.`role` AS `Account.role`, `Account`.`active` AS `Account.active`, `Account`.`createdAt` AS `Account.createdAt`, `Account`.`updatedAt` AS `Account.updatedAt`, `Account`.`practice_id` AS `Account.practice_id`
FROM
`Visits` INNER JOIN `Accounts` AS `Account` ON `Account`.`id` = `visits`.`account_id` LIMIT 10) AS `visits`
ORDER BY updatedAt DESC;
我所期待的是顶级查询的限制是这样的:
SELECT
...
FROM
(SELECT ...) AS `Visits`
ORDER BY `Visits`.updatedAt DESC LIMIT 10
LIMIT 10;
【问题讨论】:
标签: javascript mysql sequelize.js