gpt4 book ai didi

mysql - Sequelize n :m association join table with attributes

转载 作者:行者123 更新时间:2023-11-29 16:59:33 34 4
gpt4 key购买 nike

我正在尝试使用 Sequelize 在 Node JS 中构建 n: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,我尝试以这种方式将表与仪表板连接起来:

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

我收到此错误:SequelizeEagerLoadingError:Dashboards 未关联到 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com