Tuesday, August 7, 2012

Cakephp Model association on a non primary key

Issue:
City -> belongsTo -> Country

City:
id | name | country_code

Country:
id | name | code


Your city is linked to country through City.country_code = Country.code.
Now if you do the usual $belongsTo

public $belongsTo = array(
  "Country"=>array(
   'className'    => 'Country'
   )
 );

You'll find cake will join the models on PK fields
LEFT JOIN `db`.`countries` AS `Country` ON (`City`.`country_id` = `Country`.`id`)

To solve this use "condition"
public $belongsTo = array(

 "Country"=>array(
 'className'    => 'Country'
 ,'foreignKey' => false
 ,'conditions' => array('City.country_code = Country.code')
   )
  );

No comments: