Does CakePHP handle FKs on the code level or shoul

2019-06-28 01:28发布

问题:

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:

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.



回答2:

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');
}
?>