简体   繁体   English

Sequelize 在同一张桌子上的关系。 基于多对多检索数据

[英]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.我有一个名为 Users 的表,它通常包含以下字段。

User id, name, email, password, userType, jobTitle用户id、姓名、email、密码、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.我将如何定义 seuqlize 中的关系以定义特定用户的经理。

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.我想到的一种方法是使用 managerId 将另一列添加到 Users 表中,并具有作为经理的用户的 id。

Or would it be better to create a junction table called User_Manager having userID and managerID as the foreign keys?还是创建一个名为 User_Manager 的联结表,将 userID 和 managerID 作为外键会更好吗?

Which way would work best and how to define this using sequelize?哪种方式效果最好,以及如何使用 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.manager_id这样的 users 表中的列既快速又简单,并且提供了一个简单的自联接来获取经理。

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.如果您永远不需要超过经理关系 - 然后KISS并在用户表中添加列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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