【问题标题】:How to add ORDER BY into sequelize method in NodeJS如何将 ORDER BY 添加到 NodeJS 中的 sequelize 方法中
【发布时间】:2016-09-29 18:36:55
【问题描述】:

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

有两个用户表:useruser_password

如果用户至少更改了一次密码,则user_password 表中的每个用户都有多个条目。我想通过findUserWithUsername(username) 验证用户,如图所示:

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 中的第一个密码条目,但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() 方法中?

【问题讨论】:

标签: node.js sequelize.js


【解决方案1】:

也许你应该倒着做:

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

获取所有用户密码,包括该用户名

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

【讨论】:

    【解决方案2】:

    添加应该适合你

    order: 'id DESC'
    

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

    【讨论】:

      【解决方案3】:

      我认为你的代码语法有问题。

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

      应该做的伎俩。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多