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?
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.
With timestamps: false , the generated model will omit the createdAt and updatedAt attributes. You can also opt to include only the timestamp attribute you need as shown below: const User = sequelize. define( "User", { firstName: Sequelize.
hasOne(B) association means that a One-To-One relationship exists between A and B , with the foreign key being defined in the target model ( B ). The A. belongsTo(B) association means that a One-To-One relationship exists between A and B , with the foreign key being defined in the source model ( A ).
How do you include two models in Sequelize? Your solution, along with using include: {all:true} in my findAll query, did the trick. instead of using include: {all:true} in findAll you can use include: {model: models.
The current master has support for hooks.
var User = sequelize.define('User', {
username: DataTypes.STRING
}, {
hooks: {
beforeCreate: function(user, next) {
makeYourCheck(function() {
next("a string means that an error happened.")
})
}
}
})
You can check the PR for further information: https://github.com/sequelize/sequelize/pull/894
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