3

我试图2个小时解决一个不是一个小问题。 我在一个生成的yeoman Angular-fullstack应用程序。sequelize,声明(where)在声明(where)

我想与sequ​​elize写这样的代码:

SELECT * 
FROM demand 
WHERE city_id NOT IN (
SELECT city_id 
FROM demand 
WHERE user_id=req.params.user_id) 

我还没有下面的代码,但不起作用。我只得到[]

export function getCity(req, res) { 
    return Demand.findAll({ 
    where: { 
     city_id:{ $notIn: Demand.findAll({ 
     attributes: ['city_id'], 
     where: { 
      user_id: req.params.user_id, 
     } 
     })} 
    } 
    }) 
    .then(handleEntityNotFound(res)) 
    .then(respondWithResult(res)) 
    .catch(handleError(res)); 
} 

你有线索吗? 谢谢。

回答

2

我还没找到一个很好的解决方案:我终于用查询写了。

export function showDemandArtistNoUser(req, res) { 
    return db.sequelize.query('SELECT * FROM demands WHERE city_id NOT IN (SELECT city_id FROM demands WHERE user_id='+req.params.user_id+')', { type: db.sequelize.QueryTypes.SELECT }) 
    .then(handleEntityNotFound(res)) 
    .then(respondWithResult(res)) 
    .catch(handleError(res)); 
} 

而且随着我的角fullstack,我有我的页面上添加:

import db from '../../sqldb'; 
3

从你的第一个查询的问题是存在的,因为sequelize的的findall方法返回一个承诺。

使用在与sequ​​elize条件是通过字面方法子查询的唯一方法:sequelize.literal('your query');

检查这个问题,以便获得更多的信息https://github.com/sequelize/sequelize/issues/3961

1

我在项目中遇到类似的问题。 我选择来实现它的方式是有两个原因有所不同:在时间

  1. 如果在一个点Sequelize决定实行分查询 - 语法已准备就绪。
  2. 再次使用Sequelize保护SQL注入。

这是我的例子,希望它有帮助。

const sqlSubquery = sequelize.dialect.QueryGenerator.selectQuery('demand', 
    attributes: ['city_id'], 
    where: { 
     user_id: req.params.user_id 
    }) 
    .slice(0,-1); // to remove the ';' from the end of the SQL 

Demand.findAll({ 
    where: { 
     city_id: { 
      $notIn: sequelize.literal('(' + sqlSubquery + ')'), 
     } 
    } 
}); 

有些人可能会选择不使用tempSQL变量,简单地建立查找结构内部的SQL(可能使用一个辅助方法?)

我也觉得这可能是一个子查询的基础因为它几乎使用相同的语法,因此可以扩展为续集。