Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize findOrCreate with include association

Using sequelize, I have two models with associations:

var Assessment = sequelize.define("Assessment", {
  name: DataTypes.STRING
});

var User = sequelize.define("User", {
  sid: DataTypes.STRING
});

Assessment.belongsTo(User);
User.hasMany(Assessment);

After some application logic, I have a User:

User.findOrCreate( { where: {sid: "123"} } ).spread(function (user, created) {
  // user is a User
});

At this point, I cannot get sequelize to associate the User as part of a Assessment.findOrCreate. This code will create a new Assessment record in the database (if one does not exist), but it will not include the User key as part of the record (instead it's just NULL):

Assessment.findOrCreate( {
  where: { },
  include: [ { model: User, where: user.primaryKeyValues } ]
} ).spread( function (assessment, created) {
  // ...
});

I have a workaround working by adding:

assessment.setUser(user).then( function(assessment) {
   ...
});

...however, this results in a SQL UPDATE that should just be part of creating the record. I'm fairly certain there should be way to do this, but unable to find anything in the docs/so/etc.

like image 988
utopianheaven Avatar asked Mar 08 '15 23:03

utopianheaven


People also ask

How do I add an association in model 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.

What is a one-to-many relationship in Sequelize?

To create a One-To-One relationship, the hasOne and belongsTo associations are used together; To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.

Are there many relations in Sequelize?

The Sequelize hasMany() method is used to create a One-To-Many association between two Sequelize models. For example, suppose you have SQL tables named Countries and Cities in your database. These two tables are related where one country row can have many city rows.


Video Answer


1 Answers

Try this: You'd need to set the User primary key reference into the created assessment.

Assessment.findOrCreate( {
  where: { UserId: user.id },
  include: [ User ]
} ).spread( function (assessment, created) {
  // assessment should contain a User property with the previously found / created user
});
like image 54
Dan Rocha Avatar answered Sep 20 '22 05:09

Dan Rocha