Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When adding a foreign key constraint, which direction is best practice?

Imagine I have three tables called profiles, profiles_skills and skills. It's a HABTM relationship, where a profile can have many skills and a skill can belong to many profiles.

I need to set up a foreign key constraint between these tables. My question is, what direction should the foreign key be? For example, do I do this:

ALTER TABLE profiles_skills ADD FOREIGN KEY (skill_id) REFERENCES skills(id);
ALTER TABLE profiles_skills ADD FOREIGN KEY (profile_id) REFERENCES profiles(id);

Or do I do this:

ALTER TABLE profiles ADD FOREIGN KEY (id) REFERENCES profiles_skills(profile_id);  
ALTER TABLE skills ADD FOREIGN KEY (id) REFERENCES profiles_skills(skill_id);

I've never really followed a convention, I just do it the way I type it and haven't had a problem. But I've always wondered in the back of my mind if it even really matters.

like image 695
James Dawson Avatar asked Feb 16 '13 23:02

James Dawson


1 Answers

My question is, what direction should the foreign key be?

Foreign keys should be in the junction table (profiles_skills), referencing the endpoint tables (profiles and skills).

If you try to do it the other way around, you'll be able to "connect" non-existent profile and/or skill, which is exactly what foreign keys are supposed to prevent. It would also make it impossible to have an unconnected profile (or skill).

like image 88
Branko Dimitrijevic Avatar answered Oct 30 '22 09:10

Branko Dimitrijevic