Question

Given :

Group hasMany Persons

but the relationship is independent (ie. Persons can exist without belonging to a Group), should the foreign key in the persons table (ie group_id) be set to 0 (or NULL) when deleting a group? If you do not, the person will try to belong to a group that does't exist.

The reason I ask is that this is default behavior in Cakephp. If you set dependent to true, it will delete the associated models, but if it's set to false it will leave the associated model untouched.

Was it helpful?

Solution

Yes, the foreign keys should be set to NULL (or 0, if this is your chosen 'no group' value) or you lose referential integrity. If your database supports it, you should be able to set an 'On delete' trigger or a cascade rule in your framework to enforce this. And the behaviour in CakePHP seems correct. If the value is dependent, then it should be removed on deletion. If it isn't dependent then you need to give extra behaviour logic as to the correct action to take (in this case, you want to set all values to NULL. In other cases, you may want to set to a 'default' group, etc)

OTHER TIPS

In a word, yes. Leaving the foreign key on the persons table would result in the loss of referential integrity within the database.

> If you do not, the person will try to belong to a group that does't exist.

There is also a worse scenario: in the future a new group B may appear that will reuse the id of deleted group A. Then all former A group's users will be "magically" enlisted into new group B.

An alternative, more stable way to implement a situation where both entities are independent would be to remove the foreign key entirely from Person and create a join table group_persons. This way you won't have to worry about your reference integrity when deleting a group. When you delete a group, the association would be deleted from group_persons.

The table would look like this

id, group_id, person_id

The group_persons model will look like this

Person hasMany GroupPerson
Group hasMany GroupPerson
GroupPerson belongsTo Person, Group

If you want the Person to only be able to be in one group at a time, set a unique validation rule in GroupPerson.

var $validate=array(
    'person_id'=>array(
        array(
        'rule'=>'isUnique',
        'message'=>'This person is already in a group.'
        )
    )
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top