首页 > 解决方案 > Sequelize :仅返回嵌套包含的多个结果之一

问题描述

我有 3 张桌子:

  1. 职位空缺
  2. 招聘阶段
  3. 面试时段

他们的联想是,jobpost有很多招聘阶段,招聘阶段有很多面试时段

通过包含招聘阶段关联和组子句,我能够获得职位的所有招聘阶段。

const jobPosts = await JobPost.unscoped().findAll({
            where,
            include: [
            {
                model: db.RecruitmentPhase,
                include: [{
                    model: db.InterviewSlot,
                },

            ],
            group: ['RecruitmentPhases.id'],
        });

但是我只有一个招聘阶段的面试名额,尽管该招聘阶段有很多面试名额。

我试着在包含里面做组子句。

const jobPosts = await JobPost.unscoped().findAll({
                where,
                include: [
                {
                    model: db.RecruitmentPhase,
                    group: ['InterviewSlots.id'],
                    include: [{
                        model: db.InterviewSlot,
                    },

                ],
                group: ['RecruitmentPhases.id'],
            });

但它也只提供一个面试时段

编辑

岗位模型:

module.exports = (sequelize, DataTypes) => {
    const jobPost = sequelize.define('JobPost', {
        id: {
            type: DataTypes.BIGINT,
            allowNull: true,
            autoIncrement: true,
            primaryKey: true,
        },
        jobTitle: {
            type: DataTypes.STRING(150),
            allowNull: true,
        },

    }, {
        timestamps: true,
        defaultScope: {
            attributes: { exclude: ['createdAt', 'updatedAt'] },
        },
    });
    jobPost.associate = (models) => {
        jobPost.hasMany(models.RecruitmentPhase);
    };
    return jobPost;
};

招聘阶段模型:

module.exports = (sequelize, DataTypes) => {
    const recruitmentPhase = sequelize.define('RecruitmentPhase', {
        id: {
            type: DataTypes.BIGINT,
            allowNull: true,
            autoIncrement: true,
            primaryKey: true,
        },

        phaseName: {
            type: DataTypes.STRING(200),
            allowNull: true,
        },

    }, {
        timestamps: true,
    });
    recruitmentPhase.associate = (models) => {
        recruitmentPhase.belongsTo(models.JobPost);
        recruitmentPhase.hasMany(models.InterviewSlot);
    };
    return recruitmentPhase;
};

面试时段模型:

module.exports = (sequelize, DataTypes) => {
    const interviewSlot = sequelize.define('InterviewSlot', {
        id: {
            type: DataTypes.BIGINT,
            allowNull: true,
            autoIncrement: true,
            primaryKey: true,
        },
        interviewDate: {
            type: DataTypes.DATE,
            allowNull: true,
        },
    });
    interviewSlot.associate = (models) => {
        interviewSlot.belongsTo(models.RecruitmentPhase);
    };
    return interviewSlot;
};

标签: node.jssequelize.js

解决方案


删除group: ['RecruitmentPhases.id'],以查看 InterviewSlots 的详细信息。照原样,您会看到面试时段的摘要......


推荐阅读