CakePHP 2 - 许多表的外键

时间:2012-08-09 02:11:02

标签: cakephp model foreign-keys associations cakephp-2.0

请帮助模特协会。 架构看起来像: Data model schema

translation_typeofs.typeof_id是typeof_ [name]外键

translation_typeofs.typeof_type内容关系表名称的一部分(天,颜色,建筑物或房间)。

TypeofDays模型:

class TypeofDay extends AppModel {
    public $name = 'TypeofDay';

    public $hasMany = array(
        'GalleriesTypeofDay' => array(
            'className'  => 'GalleriesTypeofDay',
            'dependent' => true
        ),
        'TranslationTypeof' => array(
            'className'  => 'TranslationTypeof',
            'conditions' => array('TranslationTypeof.typeof_type' => 'days'),
            'dependent' => true
        )
    );
}

模型的翻译类型:

class TranslationTypeof extends AppModel {
    public $name = 'TranslationTypeof';

    public $belongsTo = array(
        'Language' => array(
            'className'    => 'Language',
            'foreignKey' => 'language_id',
        ),
        'TypeofBuilding' => array(
            'className'  => 'TypeofBuilding',
            'foreignKey' => 'typeof_id',
            'conditions' => array('TranslationTypeof.typeof_type' => 'buildings')
        ),
        'TypeofColour' => array(
            'className'  => 'TypeofColour',
            'foreignKey' => 'typeof_id',
            'conditions' => array('TranslationTypeof.typeof_type' => 'colours')
        ),
        'TypeofRoom' => array(
            'className'  => 'TypeofRoom',
            'foreignKey' => 'typeof_id',
            'conditions' => array('TranslationTypeof.typeof_type' => 'rooms')
        ),
        'TypeofDay' => array(
            'className'  => 'TypeofDay',
            'foreignKey' => 'typeof_id',
            'conditions' => array('TranslationTypeof.typeof_type' => 'days')
        )
    );
}

当我尝试保存数据时

$this->TranslationTypeof->saveAll(array(
    'typeof_type'   => $this->data['type_name'],
    'typeof_id'     => $this->data['type_id'],
    'language_id'   => $languageId,
    'text'          => $translation
));

我收到错误500(内部服务器错误)

错误日志:

错误:[PDOException] SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(schematranslation_typeofs,CONSTRAINT translation_typeofs_typeof_buildings_fkid1 FOREIGN KEY(typeof_id)REFERENCES typeof_buildingsid)ON UPETE NO ACTION更新无行动)

我认为它与模型关联有关,但无法找到解决方案。

1 个答案:

答案 0 :(得分:2)

由于typeof_id充当外键,具体取决于提供给它的typeof_type。所以不应该有任何数据库foreignKey约束可以适用。

所以你可以做的是:“使用PhpMyAdmin从数据库中删除foreignKey约束,然后让它与CakePHP一起处理”。请问它是否对你不起作用。