문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top