Skip to content

how to define the relations between 3 tables #6671

Closed

Description

@shuperry

I want to create a relations between 3 tables with 1 table, like:

here is my 3 tables write with sequelize models.
case:

export default (sequelize, DataTypes) => {
  return sequelize.define('Case', {
    case_id: {type: DataTypes.INTEGER, field: 'case_id', primaryKey: true},
    name: {type: DataTypes.STRING(100), defaultValue: '', field: 'name'},
    code: {type: DataTypes.STRING(100), defaultValue: '', field: 'code'},
  }, {
    timestamps: false,
    tableName: 'T_CASE'
  })
}

caseRole:

export default (sequelize, DataTypes) => {
  return sequelize.define('CaseRole', {
    role_id: {type: DataTypes.INTEGER, field: 'role_id', primaryKey: true},
    name: {type: DataTypes.STRING(100), defaultValue: '', field: 'name'}
  }, {
    timestamps: false,
    tableName: 'T_CASE_ROLE_DEF'
  })
}

user:

export default (sequelize, DataTypes) => {
  return sequelize.define('User', {
    user_id: {type: DataTypes.INTEGER, field: 'user_id', primaryKey: true},
    sid: {type: DataTypes.STRING(100), defaultValue: '', field: 'sid'},
    login_name: {type: DataTypes.STRING(100), defaultValue: '', field: 'login_name'}
  }, {
    timestamps: false,
    tableName: 'T_USER'
  })
}

I want to join these 3 tables with 1 table like:

T_CASE_ROLE_USERS

字段名 类型 备注
case_id number
role_id number
user_id number

and I want to know how to write associate method in my sequelize models, thks!!

Dialect: mysql
__Database version: 5.7.15
__Sequelize version: 3.24.3

Activity

  1. felixfbecker commented on Oct 8, 2016

    @felixfbecker
    Contributor
  2. shuperry commented on Oct 8, 2016

    @shuperry
    Author

    @felixfbecker This is 2 tables, I know this, but mine is 3 tables, I want to join 3 table with 1 table

  3. shuperry commented on Oct 8, 2016

    @shuperry
    Author

    @felixfbecker This way makes one role only belongs to one case, but I need case:role relations is n:n, and role:user relations is n:n too, help me please.

  4. alitaheri commented on Oct 8, 2016

    @alitaheri
    Contributor

    @shuperry I would suggest that you build 3 sets of 1:n relations between the join table and the other three. Your queries will be complex, but your scenario is complex as well. so:

    1. Define a model: CaseRoleUser
    2. Add three primary key attributes: case_id, role_id, user_id
    3. Associate the tables via their corresponding foreign key with belongsTo and hasMany.
  5. felixfbecker commented on Oct 8, 2016

    @felixfbecker
    Contributor

    @shuperry It is not clear to me how your tables are associated, an ER diagram would help. But as @alitaheri all types of associations are supported in some way. If you still need help, please ask on StackOverflow on Slack.

  6. shuperry commented on Oct 8, 2016

    @shuperry
    Author

    @alitaheri Thanks first, this way can created right table, and now I only need to write sequelize model.findAll() data construct myself.

    {
      cases:  [{
       roles: 
         [
           {
              role_id: 'xxx', name: 'xx', 
              users: [{user_id: 'xxx', name: 'xxx'}]
           }
        ]
      }]
    }
  7. alitaheri commented on Oct 8, 2016

    @alitaheri
    Contributor

    Well the queries will be very complex, but with include you should be able to do what you need:

    Case.findAll({
      include: [{
        model: CaseRoleUser,
        include: [{ model: Role }, {model: User }],
      }],
    });
  8. shuperry commented on Oct 9, 2016

    @shuperry
    Author

    @alitaheri I know this way, but the structure is not my need, I need Role include User, no matter, I can write the structure myself.

    {
        cases:  [{
            roles: [{
                 role_id: 'xxx', name: 'xx', 
                 users: [{
                     user_id: 'xxx', name: 'xxx'
                  }]
             }]
        }]
    }
  9. jedwards1211 commented on Feb 5, 2018

    @jedwards1211
    Contributor

    @felixfbecker OP wants to define what roles a given user has on a given case. For a given user - case association there should be not just one role, but arbitrarily many roles. In other words, a "many-to-many-to-many" association.

    I'm not a database expert but it does seem to me that in pure SQL, a single table with three foreign keys is the simplest solution for this problem. For instance in this table user Jim has read and write access to case 07A, and user Bob has read-only access to cases 23F and 24Y.

    case_id user_id role_id
    07A Jim read
    07A Jim write
    23F Bob read
    24Y Bob read

    Unfortunately it doesn't seem to me like Sequelize provides any conceptual API for a table with more than two foreign key columns?

    @shuperry (apologies for writing this before I read how you were nesting your associations, my example is a bit different...) The only solution I can think of at the moment is to split this three-way relation into two separate BelongsToMany relations: make Users and Cases have a belongsToMany association through a CaseUsers table, and the CaseUsers join table in turn has a belongsToMany association with Roles. Here is how the same relations as above would be expressed with this association strategy:

    EDIT: this solution doesn't work!

    CaseUser

    id case_id user_id
    0 07A Jim
    1 23F Bob
    2 24Y Bob

    CaseUserRole

    case_user_id role_id
    0 read
    0 write
    1 read
    2 read
    User.Cases = User.belongsToMany(Case, {through: CaseUser})
    Case.Users = Case.belongsToMany(User, {through: CaseUser})
    CaseUser.Roles = CaseUsers.belongsToMany(Role, {through: CaseUserRoles})
    
    const users = User.findAll({include: [
      {association: User.Cases, include: [
        {association: CaseUser.Roles}
      ]},
    ]})
    
    /*
    users:
    [
      {
        id: 'Jim',
        cases: [
          {
            id: '07A',
            roles: [
              {id: 'read'},
              {id: 'write'},
            ]
          }
        ]
      },
      {
        id: 'Bob',
        cases: [
          {
            id: '23F',
            roles: [{id: 'read'}]
          },
          {
            id: '24Y',
            roles: [{id: 'read'}]
          }
        ]
      }
    ]
    */
  10. jedwards1211 commented on Feb 6, 2018

    @jedwards1211
    Contributor

    @felixfbecker I realized this morning, my proposed solution to the OP's problem doesn't work. It seems to me there is really no viable way to have a many-to-many-to-many relationship in Sequelize.

  11. shuperry commented on Feb 7, 2018

    @shuperry
    Author

    @jedwards1211 Our project already finished, but still thank you, at the end time, I figured out the way you said too, this way may be the simplest way, I just did't say at here, and there is no need to rewrite the code.

  12. alfredomp commented on Feb 26, 2018

    @alfredomp

    @shuperry how did you end up solving this issue? I am having the same situation.

  13. shuperry commented on Feb 27, 2018

    @shuperry
    Author

    @alfredomp The best way is write model associate as jedwards1211 said, but the select is unimplementable, you need to do the complex select and write the structure you need.

  14. achintya03 commented on May 6, 2020

    @achintya03

    @shuperry after reading the above mentioned comments, it is still not clear to me whether you got a way(solution) to do association using SEQUELIZE, for 3 tables in 1 junction table.

    I have been facing difficulties doing this and I have the same requirement to implement many-to-many-to-many relation in one table.

    After reading docs of Sequelize
    https://sequelize.org/master/manual/advanced-many-to-many.html#many-to-many-to-many-relationships-and-beyond

    I realized that they are proposing to do A-to-B in C and then use composite key of from C (A+B) then do C-to-D in E.

    It would be helpful if you can tell me whether or not you achieved A-B-C as foreign keys in D(junction table), and if not what do you think as the best way to achieve a near-to solution.

    Can you help me with sharing the structure, considering example,Table 1 is USERS, Table 2 is GROUPS, and Table 3 is PERMISSIONS to be joined in USER_TO_GROUP_PERMISSION Table 4.

  15. Hapi-swaggerstony commented on Oct 14, 2025

    @Hapi-swaggerstony

    @shuperry after reading the above mentioned comments, it is still not clear to me whether you got a way(solution) to do association using SEQUELIZE, for 3 tables in 1 junction table.

    I have been facing difficulties doing this and I have the same requirement to implement many-to-many-to-many relation in one table.

    After reading docs of Sequelize https://sequelize.org/master/manual/advanced-many-to-many.html#many-to-many-to-many-relationships-and-beyond

    I realized that they are proposing to do A-to-B in C and then use composite key of from C (A+B) then do C-to-D in E.

    It would be helpful if you can tell me whether or not you achieved A-B-C as foreign keys in D(junction table), and if not what do you think as the best way to achieve a near-to solution.

    Can you help me with sharing the structure, considering example,Table 1 is USERS, Table 2 is GROUPS, and Table 3 is PERMISSIONS to be joined in USER_TO_GROUP_PERMISSION Table 4.

    https://honourclimatic109.github.io/I7CihGgvI68U/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions