簡體   English   中英

Sequelize 在同一張桌子上的關系。 基於多對多檢索數據

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

我有一個名為 Users 的表,它通常包含以下字段。

用戶id、姓名、email、密碼、userType、jobTitle

現在每個用戶也可以有一個經理。 我將如何定義 seuqlize 中的關系以定義特定用戶的經理。

我想到的一種方法是使用 managerId 將另一列添加到 Users 表中,並具有作為經理的用戶的 id。

還是創建一個名為 User_Manager 的聯結表,將 userID 和 managerID 作為外鍵會更好嗎?

哪種方式效果最好,以及如何使用 sequelize 來定義它?

兩種解決方案都有優點。

manager_id這樣的 users 表中的列既快速又簡單,並且提供了一個簡單的自聯接來獲取經理。

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

優點:快速簡單

缺點:如果需要更多用戶關系,則不可擴展

加入表和添加關系名稱(即經理、團隊成員等)的可能性允許更大的靈活性,但更多的設置。

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;

兩者都有優點 - 如果你有時間,那么可能是一個連接表。 如果您永遠不需要超過經理關系 - 然后KISS並在用戶表中添加列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM