Multiple relationships between two entities, is this good practice?

Deadly 提交于 2019-11-29 16:46:48

It's not that "the relationship [is] recorded twice", but that you actually have two relationships between these tables — which is perfectly fine. My only concern is, can a manager belong to the same office that (s)he's the manager of? (And relatedly: is it really true that every staff member has an office and every office has a manager who is a staff member?) If so, you have a circular dependency: you can't set the manager's office until the office exists, but you can't set the office's manager until the manager exists. As long as one or the other field is nullable, you can work around this by application logic (INSERT one, then INSERT the other, then UPDATE the first one), but it's a bit ugly. But if those are the relationships that exist, then there's not much you can do about it.

It is ok by me because regardless of the fact the the tables in the relationships are the same, the relationships are actually very different. It is correct that you can deduct that a manager works in the the office she manages, however this is rather a domain rule and doesn't de-normalize the this part of the database design. if you want to get rid of the double relationship you can always create a Managers table which will contain foreign key to Staff and Office.

A circular relationship like this is valid, from an SQL perspective, but it causes some things to become complex.

For instance, when you back up and restore the data, you have to defer creation of one of the foreign key constraints until after you restore the data. Because if you create the constraints before you fill the tables, you can't restore the manager of the office before you restore his office, and you can't restore the office before you restore its manager.

Another way of solving this instead of using a Office.Manager foreign key column is to use a boolean column Staff.IsManager which is true for the manager but false for all other staff in the given office.

This seems awkward when you want to add a new office. An office must have a manager, so you need to make the manager first. But a manager is a staff member, which must have an office, so you need to make the office first.

To break this cycle, you need to allow one to be temporarily NULL or some other untrue value, and then modify whichever you create first to refer to the second. Not impossible, just awkward.

If I were designing this, I would probably have a separate "manages" table, relating offices to mangers.

tommy

This is ok, just to show the relationship. But be aware that this may lead to an infinite loop.

staffid ->officeid -> manager -> staffid

This loop can happen When retrieving data (I faced the same situation once), so it's better to normalize this and avoid this 2-relationships issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!