0

The countries table looks like this:

iso | name
--------------------------
AD  | Andorra
AE  | United Arab Emirates
AF  | Afghanistan

...etc

My customers table has the following fields which all store a country code:

id | country_origin | current_country_study | address_country
--------------------------------------------------------
54 | BE             | GB                    | GB

I'm not sure how to link the Country model so that I can retrieve the name of the countries when I am doing a find on the Customer model. If I had one field called country_id I would be okay, but not sure how to do it with multiple fields.

BadHorsie
  • 14,135
  • 30
  • 117
  • 191

1 Answers1

1

Aliases should do the trick:

public $belongsTo = array(
    'CountryOrigin' => array(
        'className'    => 'Country',
        'foreignKey'    => 'country_origin_id'
    ),
    'CurrentCountry' => array(
        'className'    => 'Country',
        'foreignKey'    => 'current_country_id'
    ),
    ....
);

You would need to update your customers table to get the new foreign key fields.

tigrang
  • 6,767
  • 1
  • 20
  • 22
  • I thought this would work also, but aren't the models always joined by the ID field? if you specify foreign key as 'country_origin_id' wouldn't it look for a country having 'country_origin_id' equal to Customer.id? – Brian Glaz Jul 18 '12 at 17:13
  • It would look for `Country.id = Customer.current_country_id` and so on (or at least it should :] ) You would add that code to the Customer model. – tigrang Jul 18 '12 at 17:14
  • Ahh ok, sounds right. This means that the OP must modify the table structure that was originally posted. – Brian Glaz Jul 18 '12 at 17:16
  • Yea it would. I figured that would be obvious, updated the answer anyways :) – tigrang Jul 18 '12 at 17:18
  • Hmm... seems like the way to go. Wish I'd known before as modifying the table is going to be a real pain. Thanks. I will let you know how it goes. – BadHorsie Jul 19 '12 at 09:23
  • Just a thought, should it be current_country_iso instead of **id** because of the countries table primary key? – BadHorsie Jul 19 '12 at 09:45
  • Thanks it worked but I had to change the countries table primary key to **id** rather than **iso** because Cake automatically assumes **id** for a primary key. It wouldn't work as **iso** and you can't specify a value for `primaryKey` in the model association. – BadHorsie Jul 19 '12 at 10:05
  • Oh, sorry. I didn't notice you weren't using an id column for your countries table. To set the primaryKey for the countries model to something outside of default/convention you need to add `public $primaryKey = 'iso';` to your `Country` model. I think that *should* work, but I've never tried it (I've always done id, so never used it). Glad you got it working. – tigrang Jul 19 '12 at 19:13