Using Sequelize, I've created two models: User
and Login
.
Users can have more than one Login, but a login must have exactly one user, which means a Login cannot be saved without a User ID.
How do I .create
a Login with a User association all in one swoop?
Current Code (Doesn't Work)
// Set up the models var User = sequelize.define('User', {}); var Login = sequelize.define('Login', {}); Login.belongsTo(User, { onDelete: 'cascade', foreignKey: { field: 'userId', allowNull: false, } }); // Create the instances var user = User.create().then(function() { // THIS IS WHERE I WOULD LIKE TO SET THE ASSOCIATION var login = Login.create({ userId: user.get('id') }); )};
The above results in SequelizeValidationError: notNull Violation: UserId cannot be null
Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.
There are two ways you can define instance methods with Sequelize: Adding the function to the prototype object. Adding the function to the model created using ES6 class.
Assuming you have the right association between users and login, you can just create a user including a login:
User.create({ name: "name", Login: {...} },{ include: Login })
you can find more information here: http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations
First of all you need to setup the relations in both ways, like this:
// Set up the models var User = sequelize.define('User', {}); var Login = sequelize.define('Login', {}); // Set the correct associations User.hasMany(Login, {}) Login.belongsTo(User, {});
Then, you need to properly get the instances returned by the promises:
// Create the instances User.create({}).then(function(newUser) { // now you can use newUser acessors to create the login return newUser.createLogin({}); ).then(function(newLogin){ // newLogin }).catch(function(error){ // error });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With