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