繁体   English   中英

使用属性对n:m关联联接表进行排序

[英]Sequelize n:m association join table with attributes

我正在尝试使用Sequelize为Node JS中的an:m关联建立模型。
以下图片显示了我要在后端映射的内容:

Imgur

使用官方文档,我定义的模型如下:

let Dashboards = sequelize.define('Dashboards', {
    name: DataType.STRING(30),
    category: DataType.TINYINT(2)
}, {
    freezeTableName: true,
    timestamps: false,
    tableName: 'dashboards'
});

Dashboards.associate = function (models) {
    Dashboards.belongsToMany(models.Charts, {
        through: {
            unique: false,
            model: models.DashboardCharts
        },
        foreignKey: 'dashboardId'
    });
};

let Charts = sequelize.define('Charts', {
    type: DataType.INTEGER(5),
    title: DataType.STRING(30),
}, {
    freezeTableName: true,
    timestamps: false,
    tableName: 'charts'
});

Charts.associate = function (models) {
    Charts.belongsToMany(models.Dashboards, {
        through: {
            unique: false,
            model: models.DashboardCharts,
        },
        foreignKey: 'chartId'
    });
};
let DashboardCharts = sequelize.define('DashboardCharts', {
    title: {
        type: DataType.STRING(30)
    },
    color: {
        type: DataType.STRING(7)
    }
}, {
freezeTableName: true,
    timestamps: false,
    tableName: 'dashboard_charts'
});

现在,如果使用DashboardCharts,我尝试以这种方式将表与Dashboards连接:

DashboardCharts.findAll({
    include: [
        {
            model: Dashboard,
            required: true,
        }
    ]
})

我收到此错误: SequelizeEagerLoadingError:仪表板未与DashboardCharts关联! 我究竟做错了什么? 感谢任何可以帮助我的人!

我找到了解决方案:做协会时我错了。 在当前配置下,我只能索取Dashboard的图表,反之亦然。 正确的解决方案是从联接表中设置belongsTo,如下所示:

let Dashboards = sequelize.define('Dashboards', {
    name: DataType.STRING(30),
    category: DataType.TINYINT(2)
}, {
    freezeTableName: true,
    timestamps: false,
    tableName: 'dashboards'
});

let Charts = sequelize.define('Charts', {
    type: DataType.INTEGER(5),
    title: DataType.STRING(30),
}, {
    freezeTableName: true,
    timestamps: false,
    tableName: 'charts'
});


let DashboardCharts = sequelize.define('DashboardCharts', {
    dashboard_id: {
        type: DataType.INTEGER(5),
        primaryKey: true
    },
    chart_id: {
        type: DataType.INTEGER(5),
        primaryKey: true
    },
    title: {
        type: DataType.STRING(30)
    },
    color: {
        type: DataType.STRING(7)
    }
}, {
    freezeTableName: true,
    timestamps: false,
    tableName: 'dashboard_charts'
});

DashboardCharts.associate = function (models) {
    DashboardCharts.belongsTo(models.Dashboards, {
        foreignKey: 'dashboard_id',
        sourceKey: models.Dashboards.id
    });

    DashboardCharts.belongsTo(models.Charts, {
        foreignKey: 'chart_id',
        sourceKey: models.Charts.id
    });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM