admin管理员组

文章数量:1356261

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.

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.

Share Improve this question edited Mar 12, 2019 at 17:05 Pedro Machado 891 silver badge9 bronze badges asked Mar 8, 2015 at 23:21 utopianheavenutopianheaven 1,2777 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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

本文标签: javascriptsequelize findOrCreate with include associationStack Overflow