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

喜你入骨 提交于 2019-12-23 12:28:12

问题


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


来源:https://stackoverflow.com/questions/1115358/does-cakephp-handle-fks-on-the-code-level-or-should-i-be-adding-fks-to-my-db-too

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!