I am setting up a database and am at a place where I am confusing myself on some many-to-many tables. I am looking for some advice on the best way to design this for performance and scalability.
I will lay out an example of my setup and what I am trying to do below.
I have the main object table…
Account
AccountID| AccountName
-----------------------
1 | First Account
…and then the child objects to be given permissions to.
Page
PageID | PageName
------------------
1 | First Page
Control
ControlID | ControlName
-----------------------
1 | First Control
MenuItem
MenuItemID | MenuItemName
-------------------------
1 | Menu Item 1
I have a permissions table for read/write etc…
Permission
PermissionID | PermissionName
------------------------------
1 | CanRead
2 | CanWrite
3 | CanDelete
So I’m trying to tie the permission table in a many-to-many between the main objects and the child objects. I will list below what I’ve come up with and why I don’t think it’s right.
One table to rule them all
PermissionAccount
AccountID | PermissionID | ControlID | MenuItemID | PageID
----------------------------------------------------------
1 | 2 | NULL | NULL | NULL
2 | NULL | 2 | NULL | NULL
*this solution is just ugly. There can be many MenuItemID‘s assigned to a single account
One table for every object
PermissionAccountControl
AccountID | ControlID | PermissionID
------------------------------------
1 | 1 | 1
1 | 2 | 1
PermissionAccountMenuItem
AccountID | MenuItemID | PermissionID
-------------------------------------
1 | 1 | 2
1 | 2 | 1
PermissionPage
AccountID | PageID | PermissionID
---------------------------------
1 | 1 | 3
1 | 2 | 1
I am leaning more toward option two. Any thoughts or suggestions are appreciated.
You could also use polymorphic association
This method might be useful if you need to handle permissions for additional objects in your software at a later point of time. Then you won’t have to create new tables or add new columns in existing tables if you use this table structure.