tags:

views:

50

answers:

2

Hi everyone!
I'm using an ORM (SQLAlchemy, but my question is quite implementation-agnostic) to model a many-to-many relationship between a parent class and its children.. I was wondering, what would be a simple way to express the concept "one of the children is the default/main one"?

For example, I'd need to persist the following:
This Person instance has Address X and Y, the main one is Y.

I saw this implemented using a "middle" class like "PersonAddressRelation" that would contain "Person", "Address" and the "main" flag, but I think it looks a bit cumbersome.. Is there a better way?

+2  A: 

The simplest way would be to have a join table, PersonAddressRelation, and also a DefaultAddress column on the Person table that keys to the Address table.

marcumka
So the join table is handled by the ORM, while I handle just the DefaultAddress, I see.. Thanks!
Joril
+1  A: 

A couple of remarks.

  • M:N relationships don't specify 'parent' and 'child', as there's no parent nor a child: there are simply two entities having an m:n relationship via a 3rd entity (the intermediate entity).

  • 'Address' is in general not a valid entity type, as semantically it has no identity, similar to a 'name' has no identity (first name, last name). You'll see this when you look at re-using an entity instance of type Address: you won't do that in general. (though you will re-use a Customer entity instance for example, when the customer has multiple orders)

  • You want to specify an attribute on the M:N relationship (default), as it belongs there. This means that the relationship itself forms an entity (which is the intermediate entity, often it has just two FK fields forming the PK). This is called an 'objectified relationship', as the relationship itself is seen as an entity. Other examples of this are Employee m:n Department and you want to specify the StartDate an employee started for a department the employee works for.

So in general: create the intermediate entity, as it in general should be there, and add the attribute there. In this particular case with Address, be really sure you are re-using Address instances among related entities (Person). If not, merge Address with Person OR if a person can have multiple addresses, create a simple 1:n relationship between Person - Address, to normalize it out, though don't be afraid to merge address data into the entity it is related to, as often address data is really not re-used (so your m:n relationship is really not there: there's no Address instance which is related to multiple person instances.

Frans Bouma
I used the wrong terms for "parent" and "child", thanks for the correction :) As for the "address" matter, I chose the wrong example, sorry :/ Anyway your explanation is very comprehensive, thanks!
Joril