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
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)
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