noSoup
noSoup

Reputation: 81

Can Eloquent replace foreign keys in the database?

Is it really necessary to add foreign keys to the database through migrations when Eloquent handles relationships just fine through the model relations provided by hasMany(), belongsTo() etc?

If the relations are added to the migrations, you still have to add relationships in the model.

I understand having relations in the database layer does provide some benefits like blocking manual queries from deleting data that relies on other data, and providing functionality like ON DELETE CASCADE.. etc

But are there any best-practices for this?

Upvotes: 0

Views: 226

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76564

It's a conceptual necessity, not a technical one. A foreign key is a reference. Not adding a foreign key means that you do not have the reference in your database. I consider it highly substandard not to create a foreign key constraint that you are aware of. Some benefits of foreign keys:

They provide a general idea of what references what

A database admin not necessarily will use your ORM when he/she analyses your database. Having the foreign key provides some very useful information.

They protect data integrity

Databases enforce foreign key constraints. If the database does not have that constraint, then your ORM code will have to be perfect in order to protect the database against some problems. This is virtually impossible when you work in a team and there are some separate branches. Some errors will slip in sooner or later, no matter what. If you have the foreign key constraint, then you might experience the bugs instead of losing or damaging information. And I have not mentioned possible bugs in your ORM.

You have spoken about manual queries, but they are just a narrow subset of your problem-space. You could have triggers, store procedures, different apps connecting to the database, hard-coded queries in the application and so on. When you avoid creating a foreign key, then you bet that it will be unnecessary even in the far-fetched future, which is of course an assumption you shouldn't make.

Any db-level features and optimizations on foreign keys can only be used as long as the foreign keys exist

Raising db-level constraints into ORM

is a bad idea in general. Besides the fact that your application code will be your own defense against problems that not necessarily occur at that level, this way you have de-facto constraints which do not exist. Your tech stack will no longer be a stack, but some graph with a cycle.

Summary

Yes, you can avoid the creation of foreign keys, but that's a bad idea. It will look nicely at first, until you realize that it's faulty. But then the damage is already done. Best to avoid that damage and play by the book in regards of foreign keys.

Upvotes: 2

Related Questions