what are the advantages of defining a foreign key

前端 未结 5 1376

What is the advantage of defining a foreign key when working with an MVC framework that handles the relation?

I\'m using a relational database with a framework that

5条回答
  •  没有蜡笔的小新
    2020-12-15 16:26

    Whilst they may be a pain when manipulating development/test data, they have saved me a lot of hassle in production.

    Think of them as a way to maintain data integrity, especially as a safeguard against orphaned records.

    For example, if you had a database relating many PhoneNumber records to a Person, what happens to PhoneNumber records when the Person record is deleted for whatever reason? They will still exist in the database, but the ID of the Person they relate to will no longer exist in the relevant Person table and you have orphaned records.

    Yes, you could write a trigger to delete the PhoneNumber whenever a Person gets removed, but this could get messy if you accidentally delete a Person and need to rollback.

    Yes, you may remember to get rid of the PhoneNumber records manually, but what about other developers or methods you write 9 months down the line?

    By creating a Foreign Key that ensures any PhoneNumber is related to an existing Person, you both insure against destroying this relationship and also add 'clues' as to the intended data structure.

提交回复
热议问题