Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating instance with an association in Sequelize

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

like image 979
slifty Avatar asked May 01 '15 22:05

slifty


People also ask

How do I create an association in Sequelize?

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.

How do I create a Sequelized instance?

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.


2 Answers

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

like image 99
Arwed Mett Avatar answered Sep 19 '22 15:09

Arwed Mett


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 }); 
like image 32
Matheus Dal'Pizzol Avatar answered Sep 17 '22 15:09

Matheus Dal'Pizzol