I'm pulling data from a table called Visits and I want to get room information as well. The cell Visits.room_id references Rooms.id, however, CakePHP is using Visits.id instead which I'm assuming is because it's the primary key.
Here are the tables
Visits - id is primary key. I even tried setting room_id as a foreign key when creating the table
id | guest_id | room_id | arrival_date | departure_date
Rooms - id is prmary key.
id | description | max_occupancy
So basically it's doing the following in a query
where Visits.id = Rooms.id
Instead of
where Visits.room_id = Rooms.id
In my Visit Model I have the following
public $hasOne = array(
'room' => array(
'className' => 'room',
'foreignKey' => 'id'
)
);
And here's an example of a query from the VisitsController
$visits = $this->paginate('Visit', array(
'arrival_date >=' => $date
)
);
$this->set(compact('visits'));
Is there any way I can tell CakePHP to use Visit.room_id instead of Visit.id?
Try this in your Visit
model
public $belongsTo = array('Room');
instead of hasOne
.
Maybe this is what you want?
This
public $hasOne = array(
'room' => array(
'className' => 'room',
'foreignKey' => 'id'
)
);
is not set correctly. I see you are sticking to conventions, so that relation can be summarize in a one-liner like
public $hasOne = array('Room');
That's actually the advantage of conventions, you don't need to configure as much for it to work.
(and in Room Model, do public $belongsTo = array('Visit');
to have it the other way around in case you need it)
Now, getting that out of the way, rethink your relations. Check the docs, if Visit hasOne Room, then the tables should be
Visit Room
----- ----
id | etc id | visit_id
In hasOne
hasOne: the other model contains the foreign key.
So to keep your tables like you have them now, the relations should be Visit belongsTo Room
and Room hasOne Visit
(or it may have many, depends on you).
(PD. I'm assuming cake v2.x)