Sequelize fetch include data based on alias where 条件

Sequelize fetch include data based on alias where condition

我有两个表 EmployeeDepartment

Department

    const Department = Sequelize.define(
        "Department",
        {
            id: {
                type: DataTypes.INTEGER,
                autoIncrement: true,
                primaryKey: true,
            },
            name: {
                type: DataTypes.STRING,
                allowNull: false,
            },
        },
        {
            underscored: true,
            timestamps: true,
            paranoid: true,
            modelName: "Department",
            tableName: "departments",
        },
    );

    Department.associate = function (models) {
        // associations can be defined here
        models.Department.hasMany(models.Employee, {
            foreignKey: "department_id",
            as: "employees",
        });
    };

    return Department;
};

Employee

    const Employee = Sequelize.define(
        "Employee",
        {
            id: {
                type: DataTypes.INTEGER,
                autoIncrement: true,
                primaryKey: true,
            },
            name: {
                type: DataTypes.STRING,
                unique: true,
                allowNull: false,
            },
            status: {
                type: DataTypes.STRING,
                defaultValue: "active",
            },
            departmentId: {
                type: DataTypes.INTEGER,
            },
        },
        {
            underscored: true,
            timestamps: true,
            modelName: "Employee",
            tableName: "employees",
        },
    );

    Employee.associate = function (models) {
        models.Employee.belongsTo(models.Department, {
            foreignKey: "department_id",
            as: "department",
        });
    };

    return Employee;
};

现在我必须获取员工列表并放置 department_id = 1

的过滤器
const { departmentId } = req.body;

const employees = await Employee.findAll({
    include: [
        {
            model: Department,
            where: {
                id: departmentId,
            },
        },
    ],
});

我遇到了问题。部门由协会“部门”映射 无法获取数据。

我在 sequelize 文档上找到了答案


const employees = await Employee.findAll({
    include: [
        {
            association: "department", // this is the place to change 
            where: {
                id: departmentId,
            },
        },
    ],
});

学习:

  1. 我们将无法将关联和模型放在一起。
  2. 如果没有关联,我们将能够使用该模型。
  3. 如果有协会,我们就可以使用。

参考文献: https://sequelize.org/master/manual/eager-loading.html#:~:text=You%20can%20also%20include%20by%20alias%20name%20by%20specifying%20a%20string%20that%20matches%20the%20association%20alias