Answer the question
In order to leave comments, you need to log in
How do associations work in sequelizeJs?
Hello, there are 2 tables, with users and ads. I want to make a connection so that when receiving all ads, I also receive the data of the one who created the ad.
In this form, when creating the second ad, an error pops up:
SequelizeForeignKeyConstraintError: insert or update on table "ads" violates foreign key constraint "ads_id_fkey"
const users_panel = sequelize.define('users_panel', {
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true
}
})
const ads = sequelize.define('ads', {
user_panel_id: {
type: Sequelize.INTEGER,
allowNull: false
},
name: {
type: Sequelize.STRING,
allowNull: false
},
})
usersPanel.hasMany(ads, {foreignKey: 'user_panel_id', as: 'ads'});
ads.belongsTo(usersPanel, {foreignKey: 'id', as: 'user'});
sequelize.sync({force: false})
.then(data => console.log('ok'))
.catch(error => console.error(error))
ads.create(dataCreate)
ads.findAndCountAll({
where: search,
limit: 100,
offset: 0,
include: [{
as: 'user',
model: usersPanel
}]
})
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question