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.
1
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
andAddress
but this does not insure that themain_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.
3