Search code examples
javascriptdatabasesequelize.jsassociations

Creating With a more complex association structure in sequelize


I am going off this small example off the sequelize docs

https://sequelize.org/docs/v6/advanced-association-concepts/creating-with-associations/#belongsto--hasmany--hasone-association

and I am not 100% following, for our project, we have a table that has a one to many association, but also two, one to many, associations within a one to many (I know a bit hard to word that)

so Table 1 has a one to many to table 2 and table 2 has a one to many to table 3 and a one to many to table 4

and I am trying to understand how to translate that to the example in that site (url) above into something workable for myself.

I just dont fully understand how to do it.

for example, looking at the example,

  include: [{
    association: Product.User,
    include: [ User.Addresses ]
  }]

I am not sure what include means vs association means. Other examples on that page seem to use association in the same way as where include is used (I think). I also am not sure how this works with multiple layers as I described above vs this more simple example.

Now I know this is a bigger-ish type of create but we are wondering if its a pluasble thing to do vs multiple calls to create data for those other tables when creating a largr dataset vs just doing a single create like this exmaple says is possible :)

if anyone has any advice I would aapperciate it, thanks!


Solution

  • association option is just another alternative to indicate an associated model: you either use include and indicate both a model ans an alias OR use association and indicate an association which already stores an associated model and its alias.
    As for 4 tables each of which in its turn is linked as one-to-many to the next one you just need to use nested include/association options and that's all. Also if you want to get all-in-one then don't forget to indicate separate: true on each level of include/association options otherwise a generated SQL query might have too many records and you'll get the out of memory error.

    const allInOneItems = Table1.findAll({
      include: [{
        model: Table2,
        separate: true,
        include: [{
          model: Table3,
          separate: true, 
          include: [{
            model: Table4,
            separate: true, 
        }]
        }]
      }]
    })