如何将ORDER BY添加到NodeJS的sequelize方法中

我有一个nodeJS应用程序使用Sequelize访问MySQL数据库。

有两个用户表: useruser_password

如果用户至less更改了密码,则user_password表中的每个用户都有多个条目。 我想通过findUserWithUsername(username)来validation用户,如下所示:

 async findOne(query = {}, include = [] , attributes = ['id', 'username', 'email'] ) { const user = await db.user.findOne({include: include, where: query, attributes: attributes}); return user; } async findUserWithUsername(username) { const include = [ { model: db.user_password, attributes: ['id','algorithm', 'password', 'salt'], order: 'id desc' } ]; return await this.findOne({username: username}, include); // need to get last one since there could be multiples } 

这是行不通的: order: 'id desc'

基本上,这些表连接user_password并返回user_password的第一个密码条目,但order: id desc不会执行任何操作…我仍然得到第一个(最早的)条目。 以下是从findUserWithUsername()方法运行的查询:

  SELECT `user`.`id`, `user`.`username`, `user`.`email`, `user_password`.`id` AS `user_password.id`, `user_password`.`algorithm` AS `user_password.algorithm`, `user_password`.`password` AS `user_password.password`, `user_password`.`salt` AS `user_password.salt` FROM `user` AS `user` LEFT OUTER JOIN `user_password` AS `user_password` ON `user`.`id` = `user_password`.`user_id` WHERE `user`.`username` = 'joe' LIMIT 1 

所以….我怎么能添加ORDER BY id的sql等价物到findUserWithUsername()方法?

添加应该为你工作

 order: 'id DESC' 

更多的例子在这里: http : //docs.sequelizejs.com/en/latest/docs/querying/#ordering

也许你应该做倒退:

 userPassword.findAll({ include:[{model:db.user, required: true, where:{ ...add here username... }}], order: 'id desc' }) 

获取所有包含该用户名的用户密码

也许你应该检查这个问题seqeuelize问题3173

我认为你的代码的语法存在一些问题。

 order: [ ['id', 'DESC'] ] 

应该做的伎俩。

文档: http : //docs.sequelizejs.com/manual/tutorial/querying.html#ordering