替换
查询中的替换可以通过两种不同的方式完成:使用命名参数(以:
开头),或者由?
表示的未命名参数. 替换在options对象中传递.
- 如果传递一个数组,
?
将按照它们在数组中出现的顺序被替换 - 如果传递一个对象,
:key
将替换为该对象的键. 如果对象包含在查询中找不到的键,则会抛出异常,反之亦然.
sequelize.query('SELECT * FROM projects WHERE status = ?',
{ replacements: ['active'], type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
sequelize.query('SELECT * FROM projects WHERE status = :status ',
{ replacements: { status: 'active' }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
数组替换将自动处理,以下查询将搜索状态与值数组匹配的项目.
sequelize.query('SELECT * FROM projects WHERE status IN(:status) ',
{ replacements: { status: ['active', 'inactive'] }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
要使用通配符运算符 %,请将其附加到你的替换中. 以下查询与名称以“ben”开头的用户相匹配.
sequelize.query('SELECT * FROM users WHERE name LIKE :search_name ',
{ replacements: { search_name: 'ben%' }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})