替换

查询中的替换可以通过两种不同的方式完成:使用命名参数(以:开头),或者由表示的未命名参数. 替换在options对象中传递.

  • 如果传递一个数组, ? 将按照它们在数组中出现的顺序被替换
  • 如果传递一个对象, :key 将替换为该对象的键. 如果对象包含在查询中找不到的键,则会抛出异常,反之亦然.
  1. sequelize.query('SELECT * FROM projects WHERE status = ?',
  2. { replacements: ['active'], type: sequelize.QueryTypes.SELECT }
  3. ).then(projects => {
  4. console.log(projects)
  5. })
  6. sequelize.query('SELECT * FROM projects WHERE status = :status ',
  7. { replacements: { status: 'active' }, type: sequelize.QueryTypes.SELECT }
  8. ).then(projects => {
  9. console.log(projects)
  10. })

数组替换将自动处理,以下查询将搜索状态与值数组匹配的项目.

  1. sequelize.query('SELECT * FROM projects WHERE status IN(:status) ',
  2. { replacements: { status: ['active', 'inactive'] }, type: sequelize.QueryTypes.SELECT }
  3. ).then(projects => {
  4. console.log(projects)
  5. })

要使用通配符运算符 %,请将其附加到你的替换中. 以下查询与名称以“ben”开头的用户相匹配.

  1. sequelize.query('SELECT * FROM users WHERE name LIKE :search_name ',
  2. { replacements: { search_name: 'ben%' }, type: sequelize.QueryTypes.SELECT }
  3. ).then(projects => {
  4. console.log(projects)
  5. })