hun*_*tar 18 orm subquery where-clause sequelize.js
我在我的Express应用程序中使用Sequelize.我需要生成一个在WHERE子句中有子查询的查询.
SELECT *
FROM MyTable
WHERE id NOT IN (
SELECT fkey
FROM MyOtherTable
WHERE field1 = 1
AND field2 = 2
AND field3 = 3
)
Run Code Online (Sandbox Code Playgroud)
我首先通过我的模型尝试过关系/关联,但无法让它发挥作用.就像是:
MyTable.find( {
where: {
id: {
$notIn: // <= what goes here? Can I somehow reference my include model?
}
},
include: [ {
model: MyOtherTable,
where: {
field1: 1,
field2: 2,
field3: 3
} ]
} );
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用Sequelize.where(),那里没有运气.
然后我尝试了Sequelize.literal(),但是不确定它是否是在Sequelize的where子句中做一个子查询的"正确"方式,因为我是新手.
MyTable.find( {
where: {
id: {
$notIn: sequelize.literal(
'( SELECT fkey ' +
'FROM MyOtherTable ' +
'WHERE field1 = ' + field1 +
' AND field2 = ' + field2 +
' AND field3 = ' + field3 +
')'
}
}
} );
Run Code Online (Sandbox Code Playgroud)
我也知道我可以使用,Sequelize.query()但不知道我是否应该达到它或者是否literal()马上就能看到我正在忽略的东西.
我真的想知道如何WHERE使用Sequelize以"正确"的方式在子句中执行子查询.
感谢您的反馈!
Sha*_*das 21
我在我的项目中遇到过类似的问题.我选择实现它的方式有点不同,原因有两个:
这是我的代码片段,希望它有所帮助.
const tempSQL = sequelize.dialect.QueryGenerator.selectQuery('MyOtherTable',{
attributes: ['fkey'],
where: {
field1: 1,
field2: 2,
field3: 3
}})
.slice(0,-1); // to remove the ';' from the end of the SQL
MyTable.find( {
where: {
id: {
$notIn: sequelize.literal('(' + tempSQL + ')'),
}
}
} );
Run Code Online (Sandbox Code Playgroud)
有些人可能会选择不使用tempSQL变量,只是在find结构中构建SQL(也许使用帮助器方法?)
我也认为这可能是sequelize的子查询扩展的基础,因为它几乎使用相同的语法.