J
J
jenya77712018-07-19 15:46:53
Node.js
jenya7771, 2018-07-19 15:46:53

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))

And this is how I create and receive ads:
ads.create(dataCreate)
  

ads.findAndCountAll({
      where: search,
      limit: 100,
      offset: 0,
      include: [{
        as: 'user',
        model: usersPanel
      }]
    })

Please tell me, maybe there is a good article that describes how to create links, I already created 2 ( one and two ) questions about table links, but I could not get answers.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question