search

Home  >  Q&A  >  body text

How to save the owner of a group in Sequelize

I'm working with Sequelize and Koa. I created a user model and a group model using Sequelize-CLI. There is a many-to-many relationship between them. I want to store which user is the owner of the group by using his UUID. Do I create another association using a one-to-many association (1 user is the owner of 0 or more groups). I don't know how to create this association on top of many to many. Or do I just store the user's UUID in my group model? What's the best way to solve this problem? Thanks!

I searched online for examples of similar situations but found none.

P粉378264633P粉378264633496 days ago603

reply all(1)I'll reply

  • P粉410239819

    P粉4102398192023-09-14 00:33:24

    If a group can have a unique owner, then obviously you need to add something like ownerId to the Group and add an association like this:

    User.hasMany(Group, { as: 'OwnedGroups', foreignKey: 'ownerId' })
    Group.belongsTo(User, { as: 'Owner', foreignKey: 'ownerId' }

    reply
    0
  • Cancelreply