Database Relations

Sooo, i have a bit of a weird small question.

When creating the database structures, you tell the model about the relations with the other models.

Well how i work is, i don’t use migrations, I design my database and then connect to it.

Should i set the the relations, in the database, or i can just know which is a foreign key in which table and do the relations in the model. which is a better way to do it?

Should i set the foreign keys in sql, or i can just declare them in the model…what are the advantages of one of the other? I hope i am making sense!



i think the best way is to create relation in both tables and models.

If you use a database engine that supports foreign keys (and you must have good reasons to use one that doesn’t) always set foreign keys in the table definitions.

Advantages: data integrity for free.

Well, it’s not entirely free. It takes some time to write foreign key constraints. But it takes much less time than fixing corrupted databases manually later.

I use mariaDB/MySQL, after I created the tables I put the indexes on the fields needed for making the relations. Then I fire up the visual designer of phpmyadmin and define the relations by clicking. Because of this your database has the proper constraints set and that improves the integrity of your database. Also when you generate your model via gii the table bindings are coded in your model.

Thank you all for your contributions. I guess i have now made my decisions…i am going to do them in both.