Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database model Parent Child with single default child.

Is there a best practice pattern to model the following parent child relationship where exactly one child can be flagged as the default child.

I can think of two ways. Which is better or is there another better alternate?

   - ParentTable
      - Id

   - ChildTable
      - Id
      - ParentId
      - IsDefault

or

   - ParentTable
      - Id
      - DefaultChildId

   - ChildTable
      - Id
      - ParentId

like image 535
user1198207 Avatar asked Mar 24 '26 23:03

user1198207


1 Answers

I favor data models that prevent invalid data from existing at all. If you use the second approach and create a foreign key relationship between DefaultChildId and the ChildTable, then you can add constraints to ensure that your database can't ever be in an invalid state -- if you try to, say, delete a child that is somebody's default child, the database will prevent you. Using the first approach, it won't.

Specifically (as noted in a comment), ON DELETE RESTRICT constraint should be used on DefaultChildId and ON DELETE CASCADE on ParentID. This allows creation of records with more flexibility (you don't need to have a default child already there to be able to make a parent), prevents accidental deletion of default child without first updating to a new default, and intelligently handles deletion of the parent.

like image 74
Jacob Mattison Avatar answered Mar 26 '26 18:03

Jacob Mattison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!