I am trying to use Sequelize for the first time but after hours of reading documentation, blogs and issues I am still quite confused and need some help to point me in the right path to understand how associations works. This is what I have done:
EDIT: I remove from models the associate function because it works only with an index.js like this. I define the association directly in index.js before sync(). After that querying the sqlite schema confirm the field UserId is added to the table.
DB connection module:
const Sequelize = require('sequelize');
const db = new Sequelize({
host: 'localhost',
dialect: 'sqlite',
storage: './nodeapp.db.sqlite'
});
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
db.models.User.hasMany(db.models.Order);
// db.models.Order.belongsTo(db.models.User); // THIS WORKS TOO
db.sync();
console.log('Database synchronized successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
module.exports = db;
User model definition:
const DataTypes = require('sequelize');
const db = require('./index');
const User = db.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
...
});
/* REMOVED
User.associate = (models) => {
models.User.hasMany(models.Order);
};
*/
module.exports = User;
Order model definition:
const DataTypes = require('sequelize');
const db = require('./index');
const Order = db.define('Order', {
order_num: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
...
});
/* REMOVED
Order.associate = (models) => {
models.Order.belongsTo(models.User);
};
*/
module.exports = Order;
Router module:
router.post('/order',(req,res) => {
Order
.create(req.body.order)
.then(order => {
// HERE IS WHERE I'AM TRYING TO POPULATE THE RELATION WITH SET ...
order.setUser(req.body.user).then((order) => {
res.send(order);
})
.catch(error => {
res.send(error);
});
});
All the CRUD operations are working correctly if I don't consider the relations. I can't figure it out how to populate the user reference in the order model, my questions are:
- Defining the association in the model only add the foreign key field?
- I have to manually populate the foreign key with id value or I can use user Object?
I need some help figuring out where I've gone wrong here because I know I am not doing something new.