Sequelize findOrCreate with include assoication

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 User :

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

At this moment, I cannot get sequelize to bind the user as part of Assessment.findOrCreate . This code will create a new Score record in the database (if it does not exist), but it will not include the user key as part of the record (instead it is just NULL):

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

I have a workaround adding:

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

... however, this results in SQL UPDATE, which should just be part of creating the record. I am sure there must be a way to do this, but could not find anything in the / so / etc docs.

+6
source share
1 answer

Try the following: you will need to set the link to the primary key of User in the created rating.

 Assessment.findOrCreate( { where: { UserId: user.id }, include: [ User ] } ).spread( function (assessment, created) { // assessment should contain a User property with the previously found / created user }); 
+2
source

Source: https://habr.com/ru/post/983518/


All Articles