我得到了两个对象之间的一对多关系:仪表板和图表,描述如下:
module.exports = function (sequelize, DataTypes) {
const Dashboard = sequelize.define('Dashboard', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
title: {
type: DataTypes.STRING
}
});
Dashboard.associate = (models) => {
Dashboard.belongsTo(models.User, {
foreignKey: 'user_id',
targetKey: 'id'
});
Dashboard.hasMany(models.Chart, {
foreignKey: 'dashboard_id',
sourceKey: 'id'
});
};
return Dashboard;
};
和 :
module.exports = function(sequelize, DataTypes) {
var Chart = sequelize.define('Chart', {
id: {
type: DataTypes.INTEGER(32),
primaryKey: true,
autoIncrement: true
},
title: {
type: DataTypes.STRING,
allowNull: false
},
x_title: {
type: DataTypes.STRING
},
y_title: {
type: DataTypes.STRING
},
data_type: {
type: DataTypes.STRING,
allowNull: false
},
data_value: {
type: DataTypes.STRING,
allowNull: false
},
filters: {
type: DataTypes.TEXT,
allowNull: false
}
}
);
Chart.associate = (models) => {
Chart.belongsTo(models.Dashboard, {
foreignKey: 'dashboard_id',
targetKey: 'id'
});
};
return Chart;
};
因此,当我想添加一个带有多个图表的新仪表板时:
models.Dashboard.create({
user_id: 1,
title: 'Dashboard title',
charts: [
{
title: 'time',
x_title: 'Days',
y_title: 'Count',
data_type: 'count',
data_value: 'visit',
filters: '[{"type":"project","values":["1"]},{"type":"language","values":["french"]},{"type":"satisfaction","values":[1,2,3]}]'
},
{
title: 'indicator',
x_title: '',
y_title: '',
data_type: 'count',
data_value: 'visit',
filters: '[{"type":"project","values":["1","2","3","4","5","6"]},{"type":"language","values":["french"]}]'
}
]
}, { include: [models.Chart] }).then(() => {
res.send({
'message': 'Dashboard loaded !'
});
});
仪表板插入到数据库中,但没有插入图表......使用 Sequelize 添加具有一对多关联的记录的最佳方法是什么?我只是尝试并阅读所有文档( http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations ),但我不明白这种有问题的行为......
感谢您的帮助和启发!
最佳答案
在定义的关联中
Dashboard.hasMany(models.Chart, {
foreignKey: 'dashboard_id',
sourceKey: 'id'
});
foreignKey
被称为 dashboard_id
但在 dashboard_id
模型中没有 Chart
。以下代码有效
const Dashboard = sequelize.define('dashboard', {
title: Sequelize.STRING,
});
const Chart = sequelize.define('chart', {
dashboard_id: Sequelize.INTEGER,
title: Sequelize.STRING,
});
Dashboard.hasMany(Chart, {
foreignKey: 'dashboard_id',
sourceKey: 'id'
});
Dashboard.create({
title: 'one',
charts: [
{ title: 'title1' },
{ title: 'title2' }
]
}, { include: [Chart] }).then((result) => {
console.log(result);
});