CakePHP模型FK加入

时间:2015-07-02 19:37:58

标签: php cakephp model

我无法让Cake加入正确的外键。下面是Cake生成的当前SQL。

SELECT
    "AirtimeShowInstance"."id" AS "AirtimeShowInstance__id",
    "AirtimeShowInstance"."starts" AS "AirtimeShowInstance__starts",
    "AirtimeShowInstance"."ends" AS "AirtimeShowInstance__ends",
    "AirtimeShowInstance"."show_id" AS "AirtimeShowInstance__show_id",
    ...
    "AirtimeShow"."id" AS "AirtimeShow__id",
    ...
FROM
    "public"."cc_show_instances" AS "AirtimeShowInstance" 
LEFT JOIN
    "public"."cc_show" AS "AirtimeShow" 
        ON (
            "AirtimeShow"."id" = "AirtimeShowInstance"."id"
        ) 
WHERE
    1 = 1 
ORDER BY
    "AirtimeShowInstance"."starts" DESC

如果我手动更改连接参数 ("AirtimeShow"."id" = "AirtimeShowInstance"."id")("AirtimeShow"."id" = "AirtimeShowInstance"."show_id")它非常有效!

我的模特出了什么问题? :(

AirtimeShowInstance.php

class AirtimeShowInstance extends AppModel {

    public $useTable = 'cc_show_instances';

    public $hasOne = array('AirtimeShow' => array(
        'className' => 'AirtimeShow',
        'foreignKey' => 'id'
    ));

}

AirtimeShow.php

class AirtimeShow extends AppModel {

    public $useTable = 'cc_show';

    public $hasMany = array('AirtimeShowInstance' => array(
        'className' => 'AirtimeShowInstance',
        'foreignKey' => 'show_id'
    ));


}

1 个答案:

答案 0 :(得分:1)

首先,您使用了错误的关联类型,您必须使用belongsTo而不是hasOne

belongsTo关联配置的外键名称也必须是show_idid不是外键,它是其他模型/表中的引用。< / p>

另见