5

I have a data model where an association/foreign key is required. Is there any way possible to enforce that constraint during model creation without getting into a chicken/egg situation?

Let's say I have a User class which requires at least one device to be associated with it. Likewise, the device must belong to a user. Something like this (untested code, don't mind syntax errors):

User = db.define("user", {
    name: Sequelize.STRING
})

Device = db.define("device", {
    uuid: Sequelize.STRING
})

User.hasMany(Device)

I want to ensure that when create is first called, that I have all Device information as well as all User information. Keeping with "fat models, skinny controllers" I'd like to put this into my models. Is it possible to do something like this?

user = User.create(
    name: "jesse"
    device:
        uuid: "84e824cb-bfae-4d95-a76d-51103c556057"
)

Can I override the create method? Or is there some type of before save event hook I can use?

4

1 回答 1

6

当前的 master 支持 hooks。

var User = sequelize.define('User', {
  username: DataTypes.STRING
}, {
  hooks: {
    beforeCreate: function(user, next) {
      makeYourCheck(function() {
        next("a string means that an error happened.")
      })
    }
  }
})

您可以查看 PR 以获取更多信息:https ://github.com/sequelize/sequelize/pull/894

于 2013-10-31T08:40:55.887 回答