I got a One-to-Many relationship between two objects : Dashboard, and Chart, described like this :
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;
};
And :
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;
};
So when I want to add a new Dashboard with several charts like this :
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 !'
});
});
The dashboard is inserted into the database, but no charts inserted as well... What is the best way to add records with a one-to-many association using Sequelize ? I just try and try, and read all docs (http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations) but I don't understand this problematic behaviour...
Thank's for your help and your enlightening !