用条件续订连接查询

时间:2015-04-27 10:07:08

标签: join sequelize.js

我使用以下语法来选择记录:

models.account.findAll({
    attributes: ['password'],
    include: [{
            model: models.user,
            as : 'user'
    }],
    where: {
        'password': password,
        'user.email': email
        }
}).then(function(res){
    console.log(res);
});

生成以下查询:

SELECT * 
FROM   `accounts` AS `account` 
       LEFT OUTER JOIN `users` AS `user` 
                    ON `account`.`user_id` = `user`.`id` 
WHERE  `account`.`password` = 'PASSWORD' 
       AND `account`.`user.email` = 'xyz@gmail.com';
           ^^^^^^^^^^^^^^^^^^^^^^

所以它给我错误:Unknown column 'account.user.email' in 'where clause'。我只想要user.email。预期查询如下:

SELECT * 
    FROM   `accounts` AS `account` 
           LEFT OUTER JOIN `users` AS `user` 
                        ON `account`.`user_id` = `user`.`id` 
    WHERE  `account`.`password` = 'PASSWORD' 
           AND `user`.`email` = 'xyz@gmail.com';

我做错了什么???

1 个答案:

答案 0 :(得分:4)

在include部分中为users表添加where过滤器:

models.account.findAll({
  attributes: ['password'],
  include: [{
    model: models.user,
    where: {
      email: email
    }
  }],
  where: {
    password: password
  }
}).then(function(res){
  console.log(res);
});