Question

I'm experiencing an issue with sails.js using the Postgres driver:

"dependencies": {
    "sequelize": "^1.7.0",
    "pg": "^3.0.3"
}

I have an Activity model that has a hasOne relationship to 2 models and belongs to another:

classMethods: {
    associate: function(models) {
        Activity.hasOne(models.Model2);
        Activity.hasOne(models.Model3);
        Activity.belongsTo(models.User);
    }
}

The problem I am having is I seem unable to create 2 Activity Instances that share the same Model2 or Model3 row/instance. I declare the first one:

Activity.create({}).complete(function(err, activity) {
    if(err) throw err;
    activity.setUser(User_Instance_X)
    activity.setModel2(Model2_Instance_X);
    activity.setModel3(Model3_Instance_X);
    activity.save().complete(db_save_cb);
}

If I then declare another one, using the same Model2 & Model3 instance but a different user, then the first row/instance no longer contains a reference to Model2 & 3, and only the latest row/instance contains that reference.

This is puzzling functionality? Is it a lack of understanding on my part or a bug?

Was it helpful?

Solution

I'll provide the answer we figured out in comments. What OP actually wanted was belongsTo for all his associations.

belongsTo in Sequelize adds the foreign key on the source while hasOneadds the foreign key on the target.

hasOne is actually rarely ever used and is probably due for an api change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top