【问题标题】:Query records that does not have an entry in another table using Sequelize include clause使用 Sequelize 包含子句查询在另一个表中没有条目的记录
【发布时间】:2019-11-16 03:31:30
【问题描述】:

给定用户表和评分表

如何从 Users 表中查询所有在 Ratings 表中没有评分记录的用户记录使用 Sequelize 包含子句

注意:续集版本 5.x

提前致谢

【问题讨论】:

    标签: mysql orm sequelize.js


    【解决方案1】:

    您可以通过两种方式执行此操作,具体取决于您的模型是如何定义的。

    1. 使用Sequelize Eager Loading 获取所有UsersRatings。然后过滤用户没有任何评分的地方。

    const users = Users.findAll({
      include: [Ratings]
    });
    const filteredUsers = users.filter(user => user.ratings.length === 0);
    

    2.Ratings 表中获取所有userIds,然后使用notIn Sequelize operator 将这些userIds 传递给where 子句

    const ratings = Ratings.findAll({
      attributes: ["userId"],
      group: ["userId"]
    });
    const userIds = ratings.map(rating => rating.userId);
    const filteredUsers = Users.findAll({
      where: {
        userId: { [Op.notIn]: userIds }
      }
    });
    

    【讨论】:

    • 这正是我不喜欢续集的原因
    【解决方案2】:

    尝试在 where 子句中加入 sequelize 文字:

    const ratings = Ratings.findAll({
                    attributes: ["userId"],
                    group: ["userId"],
                    where: {
                             $and: [ 
                                    sequelize.literal(`NOT EXISTS (
                                            SELECT 1 FROM Ratings r
                                            WHERE r.userId = User.id
                                            )`),
                                    ],
                            },
                   });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      相关资源
      最近更新 更多