I have this database design
Applicant Table
id | country_id | country_now_id
Country Table
id | name
The country_id is an FK to the Country Table, and the country_now_id is also an FK of Country Table. My question is how would I write this one in Model relation?
I have this code:
class Applicant extends AppModel {
public $belongsTo = array(
'Country'=>array(
'className'=>'Country',
'foreignKey'=>'country_id'
),
);
.....
I don't know how to add the country_now_id and put it in that relation. I'm not even sure if using $belongsTo
is the right way. I am still new in the CakePHP Framework. Your help will be greatly appreciated!
Thank You! :)
Update: I managed to solve this one by doing this
public $belongsTo = array(
'Job'=>array(
'className'=>'Job',
'foreignKey'=>'psm_id',
),
'Country'=>array(
'className'=>'Country',
'foreignKey'=>'country_id'
),
'NowCountry'=>array(
'className'=>'Country',
'foreignKey'=>'now_country'
),
);
Try
class Applicant extends AppModel {
public $belongsTo = array(
'Country'=>array(
'className'=>'Country',
'foreignKey'=>'country_id'
),
'CountryNow' => array(
'className' => ' Country',
'foreignKey' => 'country_now_id'
)
);
.....
That way, if you do
$this->Applicant->find('all', array('contain'=>array('Country', 'CountryNow')
for example, you'll get something like
Applicant1
Country
CountryNow
Applicant2
Country
CountryNow
You are using belongsTo
the right way... for now. But we can't actually know for sure unless you explain to us why are you using this type of relation. For example, if you want one Applicant to have two countries, then ok, you're good. But is there a chance that an applicant will have more than two countries? If that could happen, then the structure of your models will become a pain. If you can, maybe rethink the logic, if not, let's hope there's always two countries always.