简体   繁体   中英

Sequelize Relationship on the same table. Retrieving Data based on many to many

I have a table called Users which typically has the following fields.

User id, name, email, password, userType, jobTitle

Now each user can have a manager as well. How would I define the relationship in seuqlize to define the manager of the specific user.

One way I have thought of is adding another column to the Users table with managerId and have the id of the user who is the manager.

Or would it be better to create a junction table called User_Manager having userID and managerID as the foreign keys?

Which way would work best and how to define this using sequelize?

Both solutions have merit.

A column in users table like manager_id is quick and easy and affords a simple self-join to get the manager.

select users.id, managers.id as manager
from users
left outer join users as managers on users.id = managers.manager_id;

Pros: quick and easy

Cons: not extendable if more user relationships are needed

Join table and the possibility to add a relationship name ie manager, team member etc allows more flexibility, but a little more setup.

select  users.id, 
        user_relationship.id as manager, 
        relationships.role
from    users
left outer join relationships on users.id = relationships.user_id and relationships.role = 'manager'
left outer join users as user_relationship on relationships.to_user_id = user_relationship.id;

Both have merit - if you have the time then maybe a join table. If you never going to need more than a manager relationship - then KISS and add the column in users table.

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