views:

211

answers:

2

Will I suffer consequences later if I add FKs with ON DELETE CASCADE and such?

If not, what naming convention should I be using for FKs within MySQL for CakePHP?

+1  A: 

You can see the naming conventions laid out here.

Cake handles FK/relationships in the code, based on your model associations and implied associations by naming conventions. You can add an extra layer of "enforcement" by defining FK relationships on the database level. If your database honours these, it's harder to shoot yourself in the foot, but it's not necessary. It adds the extra overhead of keeping the relationships in sync in Cake's models and in the database.

deceze
This is really the answer I was going for, to know that it would be creating extra overhead, as you say. My ultimate goal is to work in the most efficient way and "extra" anything is not my idea of efficiency. Thanks!
sfjedi
To my experience, Cake does not enforce FK to be valid, whereby the DB does. Like you can insert an invalid FK key, whereby the DB would reject that insert if DB FK-s are in place. I think one should know this before using Cake only to handle FK-s. (Also note that Cake's CLI schema updater does not handle DB FK-s well: it can save them but updates will fail as dependencies are not created in the right order.)
sibidiba
+1  A: 

In CakePHP, it doesn't matter if you specify FKs in the database level, however if you do, it would act as you would expect in typical database operations.

If you have 2 tables - students and courses where each student belong to a course, you can state it this way:

<?php
class Student extends AppModel {
    var $name = 'Student';

    var $belongsTo = array(
     'Course' => array(
      'className' => 'Course',
      'foreignKey' => 'course_id'
     )
    );
}
?>

The convention is to append "_id" at the back of the singular class name of the model it belongs to.

If you use CakePHP's naming conventions, you can just state:

<?php
class Student extends AppModel {
    var $name = 'Student';

    var $belongsTo = array('Course');
}
?>
KahWee Teng
AFAIK you don't even have to state `var $belongsTo = array('Course');` if you stick to Cake's naming conventions, that would be implied if there's a `course_id` field in the `students` table.
deceze