1

I'm working on a project in which I have an entity, we may call Users and another entity Address.

I want to define the entity User in a way that an user would have a collection of addresses (typically a One-To-Many relationship), but I also need an attribute of user, let it be main_address that would target a single value of the previous collection.

I would like to know if there is a conventional of doing this. The only solution I have now is to create another One-to-One relationship between Users . main_address and Address but this does not insure that the main_address will actually be part of the User . addresses collection.

I don't know if it could be important, because it's a rather theoretical question, but I'm using Doctrine 2.

Bart van Ingen Schenau
  • 71,712
  • 20
  • 110
  • 179
ibi0tux
  • 241
  • 2
  • 11
  • I could have written "good practice" or "better practice", but this wouldn't change my problem ... My question is NOT an opened question and I know I'm not the first to ask myself how to do this. I am quite sure there are some "good" solutions to my problem and I truely hope some of them will be posted here. I'll feel free to judge by myself which one seems the "best" to me. – ibi0tux Oct 26 '14 at 20:25

1 Answers1

3

Add a field main_address_id in the User entity or table that holds the ID of the Address record that is the main one. Make that a one to one relationship, if you like.

The only solution I have now is to create another One-to-One relationship between Users.main_address and Address but this does not insure that the main_address will actually be part of the User.addresses collection.

Quite right. You need another mechanism that insures that. You can either validate that in your business logic, or use a stored procedure or trigger on the RDBMS during creation or editing of User that enforces this restriction.

Doctrine might have a "business rules" module that you can use. The point is that the additional restriction you are imposing on main_address_id doesn't have anything to do with your database schema, per se. It's a business rule, basically.

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
  • `You need another mechanism that insures that`. Ok. I hope there could be a solution involving only the data models. My idea was there could be a way to make the `main_address_id` refers to an item of the collection, rather to an Address – ibi0tux Oct 26 '14 at 20:35
  • I think finagling the model in that way would pollute it too much. The model is intended to describe the business's data domain, not necessarily to capture all of its rules. – Robert Harvey Oct 26 '14 at 20:38
  • I don't really share your point of view but I don't think it's a good idea to debate on this. Thank you for your help, i'm fixed now. – ibi0tux Oct 26 '14 at 20:44