Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm a bit confused about how that relationship table would look. Is anybody kind enough to show a concrete example?


This type of setup is semi-common and I've seen it called "polymorphic relationships". The PHP framework Laravel has first-party support for them if you want a real example, although those are generally only polymorphic for one side of the relationship (i.e. building a CRM and having a single "comments" table with the ability to relate Customers, Opportunity, Leads, etc. to each comment without having a unique column for each type).

Generally, the relationship table will look like this:

  - relation1_id
  - relation1_type
  - relation2_id
  - relation2_type
Where *_id is the database ID and *_type is some kind of string constant representing another table. Generally you put an index on "relation#_id, relation#_type", but that's obviously use case dependent


Like other have said, you can store the table types with the ids.

But here's the neat part. That's often only for safety.

If I want to find all users and their orders, I can join the user table to the relationship table, then join that to the order table. Something like:

SELECT <COLUMNS GO HERE> FROM USER INNER JOIN RELATIONSHIP ON USER.Id IN (RELATIONSHIP.LeftId, RELATIONSHIP.RightId) INNER JOIN ORDER ON ORDER.Id IN (RELATIONSHIP.LeftId, RELATIONSHIP.RightId)

So you're getting the Users. The filtering the ones that have relationships, then filtering that to the ones that also have orders.

If you've ever managed an N:N relationship table, it's like that, but more generic.


IIRC, we had a nullable column for each ID type. So a column for user, company, appointment, etc. then we had an enumerated column for the relation (owner, patient, vendor, etc).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: