1

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 Answer 1

1

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

2
  • Thanks NDM. I'd tried that solution already - However Cake reports that that the column doesn't exist (because it doesn't!) Error: SQLSTATE[42703]: Undefined column: 7 ERROR: column AirtimeShow.show_id does not exist LINE 1: ...LEFT JOIN "public"."cc_show" AS "AirtimeShow" ON ("AirtimeSh... ^ Jul 2, 2015 at 20:22
  • @ScottRobinson It's a little late, I didn't payed enough attention. Actually you should use a belongsTo association, as the docs state, in a hasOne association the other model has the foreign key.
    – ndm
    Jul 2, 2015 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.