Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize.js - model association during "create" or "build" call

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?

like image 535
Jesse Fulton Avatar asked Oct 28 '13 16:10

Jesse Fulton


People also ask

How do I create an association in Sequelize?

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.

How do you prevent createdAt and updatedAt in Sequelize?

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.

What are associations in 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?

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.


1 Answers

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

like image 122
sdepold Avatar answered Nov 15 '22 08:11

sdepold