我正在尝试使用 Sequelize 在 Node JS 中为 n:m 关联构建模型。
下面的图像显示了我试图在后端映射的内容:
使用官方文档,我定义的模型如下:
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: Dashboards is not associated to 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
});
};
关于mysql - Sequelize n :m association join table with attributes,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52371188/