Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does CakePHP handle FKs on the code level or should I be adding FKs to my db too?

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?

like image 796
jedmao Avatar asked Feb 28 '23 13:02

jedmao


2 Answers

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.

like image 52
deceze Avatar answered Mar 03 '23 20:03

deceze


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');
}
?>
like image 33
KahWee Teng Avatar answered Mar 03 '23 19:03

KahWee Teng