模型查询

    对于有查询的配置项的接口是 FindOptions。这个接口在 3188 行。而且接口上面也有英文注释,说明了如何使用。平常所用到的并不会那么难以配置,所以接下来会有一些常用。

    指定特定属性字段

    1. User.findAll({
    2. attributes: ['name', 'email']
    3. });

    重命名(将 name 重命名为 username)

    1. User.findAll({
    2. attributes: [['name', 'username'], 'email']
    3. });

    添加一个新的字段属性,通过函数来计算它的值

    1. Like.findAll({
    2. attributes: [[sequelize.fn('COUNT', sequelize.col('type')), 'post_like_count']],
    3. where: { id: 2, type: 'post'}
    4. });

    post_like_count 为 id =2 ,type = post 的结果行数。当前语句查出来只有 post_like_count 一个字段。

    假如希望保留原来默认的所以字段,然后再添加这个新的函数字段,可以使用 attributes.include 选项。

    1. Like.findAll({
    2. attributes: { include: [sequelize.fn('COUNT', sequelize.col('type')), 'post_like_count'] },
    3. where: { id: 2, type: 'post'}
    4. });

    排除字段属性

    普通用法(等于)

    最简单的用法就是在 where 里面写下键值对,左边属性,右边值。

    1. where: {
    2. authorId: 2
    3. }
    4. });

    字段操作符

    相比较之前的值,现在变成了配置项。

    1. Post.findAll({
    2. where: {
    3. authorId: {
    4. }
    5. }
    6. });
    1. $and: {a: 5} // AND (a = 5)
    2. $or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6)
    3. $gt: 6, // > 6
    4. $gte: 6, // >= 6
    5. $lt: 10, // < 10
    6. $lte: 10, // <= 10
    7. $ne: 20, // != 20
    8. $eq: 3, // = 3
    9. $not: true, // IS NOT TRUE
    10. $between: [6, 10], // 在 6 - 10 之间
    11. $notBetween: [11, 15], // 不再 11 - 15 之间
    12. $in: [1, 2], // 在数组 [1, 2] 里面
    13. $notIn: [1, 2], // 不在数组 [1, 2] 里面
    14. $like: '%hat', // LIKE '%hat'
    15. $like: { $any: ['cat', 'hat']}

    并且操作符是支持嵌套的。

    1. rank: {
    2. $or: {
    3. $lt: 1000,
    4. $gt: 900
    5. }

    900 < rank < 1000

    title LIKE 'Boat%' OR description LIKE '%boat%' 查询 title 或者 description 有关 boat 的数据。

    在实现分页功能的时候,需要限定返回的数据与偏移量。

    1. Project.findAll({ limit: 10 }) // 限定 10 条
    2. Project.findAll({ offset: 8 } // 忽略掉前 8 条

    DESC - ASC

    根据 createdAt 从大到小

    1. Project.findAll({
    2. order: ['createdAt', 'DESC']
    3. })

    根据 age 排序

    1. Person.findAll({
    2. order: sequelize.fn('max', sequelize.col('age'))
    3. })

    根据 age 从大到小排序

    1. Person.findAll({
    2. order: sequelize.literal('max(age) DESC')
    3. })

    根据相关联的 Task 模型的 createdAt 从大到小排序

    1. ItemTag.findAll({
    2. attributes: { include: [sequelize.fn('COUNT', sequelize.col('type_id')), 'post_tag_counts'], exclude: ['type_id', 'type'] },
    3. where: {
    4. type: 'post'
    5. },
    6. group: 'tag_id'
    7. })

    该语句会查出,tag 与 几篇 Post 相建立关系。假如不加 group,查出来的数据会有一些没用的,所以我们通过 group 过滤掉重复的 tag_id