Querying - 查询

    1. SELECT foo, bar ...

    属性可以使用嵌套数组来重命名:

    1. Model.findAll({
    2. attributes: ['foo', ['bar', 'baz']]
    3. });
    1. SELECT foo, bar AS baz ...

    也可以使用 sequelize.fn 来进行聚合:

    1. Model.findAll({
    2. attributes: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
    3. });
    1. SELECT COUNT(hats) AS no_hats ...

    使用聚合功能时,必须给它一个别名,以便能够从模型中访问它。 在上面的例子中,您可以使用 instance.get('no_hats') 获得帽子数量。

    有时,如果您只想添加聚合,则列出模型的所有属性可能令人厌烦:

    1. // This is a tiresome way of getting the number of hats...
    2. Model.findAll({
    3. attributes: ['id', 'foo', 'bar', 'baz', 'quz', [sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
    4. });
    5. // This is shorter, and less error prone because it still works if you add / remove attributes
    6. Model.findAll({
    7. attributes: { include: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] }
    8. });
    1. SELECT id, foo, bar, baz, quz, COUNT(hats) AS no_hats ...

    同样,它也可以删除一些指定的属性:

    1. SELECT id, foo, bar, quz ...

    无论您是通过 findAll/find 或批量 updates/destroys 进行查询,都可以传递一个 where 对象来过滤查询。

    where 通常用 attribute:value 键值对获取一个对象,其中 value 可以是匹配等式的数据或其他运算符的键值对象。

    也可以通过嵌套 orand 运算符 的集合来生成复杂的 AND/OR 条件。

    1. const Op = Sequelize.Op;
    2. Post.findAll({
    3. where: {
    4. authorId: 2
    5. }
    6. });
    7. // SELECT * FROM post WHERE authorId = 2
    8. Post.findAll({
    9. where: {
    10. authorId: 12,
    11. status: 'active'
    12. }
    13. });
    14. // SELECT * FROM post WHERE authorId = 12 AND status = 'active';
    15. Post.findAll({
    16. where: {
    17. [Op.or]: [{authorId: 12}, {authorId: 13}]
    18. }
    19. });
    20. // SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
    21. Post.findAll({
    22. where: {
    23. authorId: {
    24. [Op.or]: [12, 13]
    25. }
    26. }
    27. });
    28. // SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
    29. Post.destroy({
    30. where: {
    31. status: 'inactive'
    32. }
    33. });
    34. // DELETE FROM post WHERE status = 'inactive';
    35. Post.update({
    36. updatedAt: null,
    37. }, {
    38. where: {
    39. deletedAt: {
    40. [Op.ne]: null
    41. }
    42. }
    43. });
    44. // UPDATE post SET updatedAt = null WHERE deletedAt NOT NULL;
    45. Post.findAll({
    46. where: sequelize.where(sequelize.fn('char_length', sequelize.col('status')), 6)
    47. });
    48. // SELECT * FROM post WHERE char_length(status) = 6;
    1. const Op = Sequelize.Op
    2. [Op.or]: [{a: 5}, {a: 6}] // (a = 5 或 a = 6)
    3. [Op.gt]: 6, // id > 6
    4. [Op.gte]: 6, // id >= 6
    5. [Op.lt]: 10, // id < 10
    6. [Op.lte]: 10, // id <= 10
    7. [Op.ne]: 20, // id != 20
    8. [Op.eq]: 3, // = 3
    9. [Op.not]: true, // 不是 TRUE
    10. [Op.between]: [6, 10], // 在 6 和 10 之间
    11. [Op.in]: [1, 2], // 在 [1, 2] 之中
    12. [Op.notIn]: [1, 2], // 不在 [1, 2] 之中
    13. [Op.like]: '%hat', // 包含 '%hat'
    14. [Op.notLike]: '%hat' // 不包含 '%hat'
    15. [Op.iLike]: '%hat' // 包含 '%hat' (不区分大小写) (仅限 PG)
    16. [Op.notILike]: '%hat' // 不包含 '%hat' (仅限 PG)
    17. [Op.regexp]: '^[h|a|t]' // 匹配正则表达式/~ '^[h|a|t]' (仅限 MySQL/PG)
    18. [Op.notRegexp]: '^[h|a|t]' // 不匹配正则表达式/!~ '^[h|a|t]' (仅限 MySQL/PG)
    19. [Op.iRegexp]: '^[h|a|t]' // ~* '^[h|a|t]' (仅限 PG)
    20. [Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (仅限 PG)
    21. [Op.like]: { [Op.any]: ['cat', 'hat']} // 包含任何数组['cat', 'hat'] - 同样适用于 iLike 和 notLike
    22. [Op.overlap]: [1, 2] // && [1, 2] (PG数组重叠运算符)
    23. [Op.contains]: [1, 2] // @> [1, 2] (PG数组包含运算符)
    24. [Op.contained]: [1, 2] // <@ [1, 2] (PG数组包含于运算符)
    25. [Op.any]: [2,3] // 任何数组[2, 3]::INTEGER (仅限PG)
    26. [Op.col]: 'user.organization_id' // = 'user'.'organization_id', 使用数据库语言特定的列标识符, 本例使用 PG

    范围选项

    所有操作符都支持支持的范围类型查询。

    请记住,提供的范围值也可以。

    1. // 所有上述相等和不相等的操作符加上以下内容:
    2. [Op.contains]: 2 // @> '2'::integer (PG range contains element operator)
    3. [Op.contains]: [1, 2] // @> [1, 2) (PG range contains range operator)
    4. [Op.contained]: [1, 2] // <@ [1, 2) (PG range is contained by operator)
    5. [Op.overlap]: [1, 2] // && [1, 2) (PG range overlap (have points in common) operator)
    6. [Op.adjacent]: [1, 2] // -|- [1, 2) (PG range is adjacent to operator)
    7. [Op.strictLeft]: [1, 2] // << [1, 2) (PG range strictly left of operator)
    8. [Op.strictRight]: [1, 2] // >> [1, 2) (PG range strictly right of operator)
    9. [Op.noExtendRight]: [1, 2] // &< [1, 2) (PG range does not extend to the right of operator)
    10. [Op.noExtendLeft]: [1, 2] // &> [1, 2) (PG range does not extend to the left of operator)

    组合

    1. {
    2. rank: {
    3. [Op.or]: {
    4. [Op.lt]: 1000,
    5. [Op.eq]: null
    6. }
    7. }
    8. }
    9. // rank < 1000 OR rank IS NULL
    10. {
    11. createdAt: {
    12. [Op.lt]: new Date(),
    13. [Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000)
    14. }
    15. }
    16. // createdAt < [timestamp] AND createdAt > [timestamp]
    17. {
    18. [Op.or]: [
    19. {
    20. title: {
    21. [Op.like]: 'Boat%'
    22. }
    23. },
    24. {
    25. description: {
    26. [Op.like]: '%boat%'
    27. }
    28. }
    29. ]
    30. }
    31. // title LIKE 'Boat%' OR description LIKE '%boat%'

    运算符别名

    Sequelize 允许将特定字符串设置为操作符的别名 -

    1. const Op = Sequelize.Op;
    2. const operatorsAliases = {
    3. $gt: Op.gt
    4. }
    5. const connection = new Sequelize(db, user, pass, { operatorsAliases })
    6. [Op.gt]: 6 // > 6
    7. $gt: 6 // 等同于使用 Op.gt (> 6)

    运算符安全性

    使用没有任何别名的 Sequelize 可以提高安全性。

    一些框架会自动将用户输入解析为js对象,如果您无法清理输入,则可能会将具有字符串运算符的对象注入到 Sequelize。

    不带任何字符串别名将使运算符不太可能被注入,但您应该始终正确验证和清理用户输入。

    由于向后兼容性原因Sequelize默认设置以下别名 -

    $eq, $ne, $gte, $gt, $lte, $lt, $not, $in, $notIn, $is, $like, $notLike, $iLike, $notILike, $regexp, $notRegexp, $iRegexp, $notIRegexp, $between, $notBetween, $overlap, $contains, $contained, $adjacent, $strictLeft, $strictRight, $noExtendRight, $noExtendLeft, $and, $or, $any, $all, $values, $col

    ne, not, in, notIn, gte, gt, lte, lt, like, ilike, $ilike, nlike, $notlike, notilike, .., between, !.., notbetween, nbetween, overlap, &&, @>, <@

    为了更好的安全性,建议使用 Sequelize.Op,而不是依赖任何字符串别名。 您可以通过设置operatorsAliases选项来限制应用程序需要的别名,请记住要清理用户输入,特别是当您直接将它们传递给 Sequelize 方法时。

    1. const Op = Sequelize.Op;
    2. // 不用任何操作符别名使用 sequelize
    3. const connection = new Sequelize(db, user, pass, { operatorsAliases: false });
    4. // 只用 $and => Op.and 操作符别名使用 sequelize
    5. const connection2 = new Sequelize(db, user, pass, { operatorsAliases: { $and: Op.and } });

    如果你使用默认别名并且不限制它们,Sequelize会发出警告。如果您想继续使用所有默认别名(不包括旧版别名)而不发出警告,您可以传递以下运算符参数 -

    JSON 数据类型仅由 PostgreSQL,SQLite 和 MySQL 语言支持。

    PostgreSQL

    PostgreSQL 中的 JSON 数据类型将值存储为纯文本,而不是二进制表示。 如果您只是想存储和检索 JSON 格式数据,那么使用 JSON 将占用更少的磁盘空间,并且从其输入数据中构建时间更少。 但是,如果您想对 JSON 值执行任何操作,则应该使用下面描述的 JSONB 数据类型。

    MSSQL

    MSSQL 没有 JSON 数据类型,但是它确实提供了对于自 SQL Server 2016 以来通过某些函数存储为字符串的 JSON 的支持。使用这些函数,您将能够查询存储在字符串中的 JSON,但是任何返回的值将需要分别进行解析。

    1. // ISJSON - 测试一个字符串是否包含有效的 JSON
    2. User.findAll({
    3. where: sequelize.where(sequelize.fn('ISJSON', sequelize.col('userDetails')), 1)
    4. })
    5. // JSON_VALUE - 从 JSON 字符串提取标量值
    6. User.findAll({
    7. attributes: [[ sequelize.fn('JSON_VALUE', sequelize.col('userDetails'), '$.address.Line1'), 'address line 1']]
    8. })
    9. User.findAll({
    10. where: sequelize.where(sequelize.fn('JSON_VALUE', sequelize.col('userDetails'), '$.address.Line1'), '14, Foo Street')
    11. })
    12. // JSON_QUERY - 提取一个对象或数组
    13. attributes: [[ sequelize.fn('JSON_QUERY', sequelize.col('userDetails'), '$.address'), 'full address']]
    14. })

    JSONB 可以以三种不同的方式进行查询。

    嵌套对象

    1. {
    2. meta: {
    3. video: {
    4. url: {
    5. [Op.ne]: null
    6. }
    7. }
    8. }
    9. }

    嵌套键

    1. {
    2. "meta.audio.length": {
    3. [Op.gt]: 20
    4. }
    5. }

    外包裹

    1. {
    2. "meta": {
    3. [Op.contains]: {
    4. site: {
    5. url: 'http://google.com'
    6. }
    7. }
    8. }
    9. }
    1. // 找到所有具有至少一个 task 的 project,其中 task.state === project.state
    2. Project.findAll({
    3. include: [{
    4. model: Task,
    5. where: { state: Sequelize.col('project.state') }
    6. }]
    7. })
    1. // 获取10个实例/行
    2. Project.findAll({ limit: 10 })
    3. // 跳过8个实例/行
    4. Project.findAll({ offset: 8 })
    5. // 跳过5个实例,然后取5个
    6. Project.findAll({ offset: 5, limit: 5 })

    order 需要一个条目的数组来排序查询或者一个 sequelize 方法。一般来说,你将要使用任一属性的 tuple/array,并确定排序的正反方向。

    1. Subtask.findAll({
    2. order: [
    3. // 将转义标题,并根据有效的方向参数列表验证DESC
    4. ['title', 'DESC'],
    5. // 将按最大值排序(age)
    6. sequelize.fn('max', sequelize.col('age')),
    7. // 将按最大顺序(age) DESC
    8. [sequelize.fn('max', sequelize.col('age')), 'DESC'],
    9. // 将按 otherfunction 排序(`col1`, 12, 'lalala') DESC
    10. [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
    11. // 将使用模型名称作为关联的名称排序关联模型的 created_at。
    12. [Task, 'createdAt', 'DESC'],
    13. // Will order through an associated model's created_at using the model names as the associations' names.
    14. [Task, Project, 'createdAt', 'DESC'],
    15. // 将使用关联的名称由关联模型的created_at排序。
    16. ['Task', 'createdAt', 'DESC'],
    17. // Will order by a nested associated model's created_at using the names of the associations.
    18. ['Task', 'Project', 'createdAt', 'DESC'],
    19. // Will order by an associated model's created_at using an association object. (优选方法)
    20. [Subtask.associations.Task, 'createdAt', 'DESC'],
    21. // Will order by a nested associated model's created_at using association objects. (优选方法)
    22. [Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],
    23. // Will order by an associated model's created_at using a simple association object.
    24. [{model: Task, as: 'Task'}, 'createdAt', 'DESC'],
    25. // 嵌套关联模型的 created_at 简单关联对象排序
    26. [{model: Task, as: 'Task'}, {model: Project, as: 'Project'}, 'createdAt', 'DESC']
    27. ]
    28. // 将按年龄最大值降序排列
    29. order: sequelize.literal('max(age) DESC')
    30. // 按最年龄大值升序排列,当省略排序条件时默认是升序排列
    31. order: sequelize.fn('max', sequelize.col('age'))
    32. // 按升序排列是省略排序条件的默认顺序
    33. order: sequelize.col('age')
    34. // 将根据方言随机排序 (而不是 fn('RAND') 或 fn('RANDOM'))
    35. order: sequelize.random()

    表提示通过指定某些选项来覆盖 mssql 查询优化器的默认行为。 它们只影响该子句中引用的表或视图。