简体   繁体   中英

Seed data in Sequelize with Many-to-Many Relationship

I have messed around with trying to get some default data for my application to seed into my PostgreSQL database using sequelize. So far I have only found one way to do it, and it's not ideal.

My main question is if anyone here knows the "best practice" way to do it.

So far I have tried using Seeds, injecting the default information after syncing each model, and finally I have fallen back to requiring files that define how I want to inject the default information after models.sequelize.sync() in the main app.js file.

Seeding : This method seems to fall apart when doing much more than dumping data into the database, associations, namely the classmethods, (to my knowledge) cannot be used here which makes updating a Many-To-Many relationship nearly impossible.

Model Definition : The issue with injecting default information with associations into the model is that you have to somehow import the other model definitions into the model, which I couldn't seem to get working right.

At this point I'm not so interesting in picking apart code as much as I am seeking what you would think/know to be the best way to get default data that has associations into the database. It seems like this would be a more popular issue since almost every app ships with at least a few pieces of default information. I would love to be told that I completely overlooked something and it's actually pretty simple :)

Thanks for the discussion in advance.

We don't need to do anything extra if we have our model associations defined already. Lets take an example where doctor can have more than one speciality. In the model definition, we can define our associations.

classMethods: {
      associate: function (models) {
        models.doctor.hasMany(models.specialty, {foreignKey: 'doctor_npi'});
      }

Now we can create an insert function and call this from seeding

insertDoctor: function (models, firstname, lastname, specialties) {
        return this.create({
          firstname: firstname,
          lastname: lastname,
          specialties: specialties,
        }, {
          include: [models.specialty],
        });
      }

Calling this function with right parameters should work.

There are more examples in the official documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM