dongtaihui5131 2015-07-02 19:37
浏览 7
已采纳

CakePHP模型FK加入

I'm having trouble getting Cake to join on the correct foreign keys. Below is the current SQL that Cake produces.

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

If I change the join parameter manually from ("AirtimeShow"."id" = "AirtimeShowInstance"."id") to ("AirtimeShow"."id" = "AirtimeShowInstance"."show_id") it works fantastically!

What's wrong with my Models? :(

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条回答 默认 最新

  • dongzhun6952 2015-07-02 19:56
    关注

    First things first, you are using the wrong assocciation type, you must use a belongsTo one instead of a hasOne.

    And the name of the foreign key for the belongsTo association config must be show_id too, id is not a foreign key, it's the reference in the other model/table.

    See also

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条