Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set association at the time of save/create in sequelizejs?

Tags:

sequelize.js

For a simple model like this:

var User = sequelize.define('User', { email: Sequelize.STRING });
var Team = sequelize.define('Team', { name: Sequelize.STRING });
User.belongsTo(Team);

Team.create({name:'blah'});

How do you store a new User and set its TeamId at the same time (same time here means in one INSERT)

This is important for cases where REFERENCE is mandatory (NOT NULL) and usual user.setTeam(team) which generates an UPDATE after an INSERT is not going to work.

Obviously extra team as an property in User.create({ email: 'x', team: team }) will be ignored and the following:

var user = User.build({email:'x'});
user.setTeam(team);
user.save();

generates one extra and completely wrong INSERT:

INSERT INTO `Users` (`TeamId`,`updatedAt`,`createdAt`) 
VALUES (4,'2015-08-19 18:10:36','2015-08-19 18:10:36');  
-- has no id or email
like image 406
el_shayan Avatar asked Aug 19 '15 18:08

el_shayan


1 Answers

Old question, but maybe someone will benefit from this answer.

Assuming that team instance you want to add is already saved in database, you can add save parameter set to false, when adding association:

var user = User.build({email:'x'});
user.setTeam(team, {save: false});
user.save();

I've spent ages looking for that solution, I dont know why documentation doesn't mention it (or I couldn't find it there)

like image 61
xersiee Avatar answered Oct 03 '22 08:10

xersiee