Relations in database or code?

I have always let my code handle relations in web applications, and Yii framwork makes that easy as well. But it has come to my understanding that a lot of people think this is bad practice. Also someone at Orcale/MySQL said to my boss that relations should be in the database.

I would like to hear from the community what do you do yourself, and/or what do think is best?

Relations should be in the database. Their proper name in DBA world is Foreign Keys.
Your Yii relations should always reflect FK!


I agree with @evstevemd . Relations are better built in database. I remember reading somewhere that building them in database is also better for performance.

Another advantage of this approach when comes to Yii is that, if you are using the Yii generators, it creates all code automatically based on the relations you have on your database.


You have to write your code to handle relations in application layer anyway anyhow, even when you have established them in DB layer using foreign-key constraints. The latter won’t make the former useless.

But it is always better to establish foreign-key constraints in database. It will make database far more consistent, solid and fast.

And as @gabrielsomi says, Yii’s code generator (Gii) will make full use of FK constraints in database when it genarates the code and eliminates some of your toil.

Thank you for the answers!
I am switching to using relations in database now. :slight_smile: