I am trying to associate a User model and an Age model with a many to many relationship. The user and age model are being created however the through table isn't. Here is my code:
const { Sequelize, Op, QueryTypes } = require('sequelize')
const db = new Sequelize('postgres://localhost:5432/sqlstuff', {
logging: false
})
const Age = db.define('Age', { age: Sequelize.INTEGER }, { timestamps: false })
const User = db.define('User', {
firstName: Sequelize.STRING,
lastName: Sequelize.STRING,
}, { timestamps: false })
async function create() {
try {
//Both Users and Ages Table are created. Both tables are properly populated
const people = await User.bulkCreate([
{ firstName: 'Tyler', lastName: 'Kumar'},
{ firstName: 'Sabi', lastName: 'Kumar'}
], { validate: true }, { fields: ['firstName', 'lastName']})
const myAge = await Age.create({ age: 22 })
//Line 21 and 22 do not create a through table, unsure why
User.belongsToMany(Age, { through: 'UserAges' })
Age.belongsToMany(User, { through: 'UserAges' })
//Line 23 creates the error 'relation "UserAges" does not exist'
await people[1].addAge(myAge)
} catch (error) {
console.error(error)
}
}
async function connect() {
try {
await db.sync({ force: true })
await create()
await db.close()
} catch (error) {
console.error(error)
}
}
connect()