Cakephp: HasOne Relationship

Chris picture Chris · Dec 22, 2010 · Viewed 13.2k times · Source

I'm trying to model the following:

A journey has an id, a fromCity and a toCity.

My DB looks like this:

Table journey:

id | fromCity | toCity
1    2           4
2    4           2

Table fromCity:

id  | name
2     paris
4     london     

I have models defined for the city and for the journey.

In my model file for the journey I want to declare a $hasOne filed in order resolve the fromCity id to the city's name.

I tried to follow the CakePHP tutorial on hasOne (http://book.cakephp.org/view/80/hasOne) but I can't wrap my head around how to resolve two foreign keys.

Can someone please explain to me how a var $hasone = ... has to look for this case?

Edit: The models:

<?php class City extends AppModel { var $name='City';} ?> 

<?php class Journey extends AppModel { var $name='Journey'; /*var $hasOne=array(...)*/} ?>

Edit 2:

var $hasOne = array(
   'CityFrom' => array(
      'className'    => 'City',
      'conditions'   => 'Journey.fromAirport = CityFrom.id',
      'dependent'    => true,
      'foreignKey'  => 'id = Journey.fromCity'    ),
   'CityTo' => array (
      'className' => 'City',
      'conditions'   => 'Journey.toCity = CityTo.id',
      'dependent' => true,
      'foreignKey' => 'id = Journey.toCity'
   )
   );

Seems to work for the first entry of the journey table. All other's values are null. I think the problem occours from having two columns with the same name in this query.

Answer

Young picture Young · Dec 23, 2010

As Rin mentioned,you need to use beLongsTo instead of hasOne.Here's a example about Multiple relations to the same model from Cookbook.Hope it helps.