我是CakePHP的新手,在弄清楚如何设置模型关联方面有些麻烦。
假设我有3个表格:付款,预订和Reservation_details,包含以下数据
table reservations
id | confirmation_number | guest_id
1 123 1
table reservation_details -a reservation can have multiple entries (multiple rooms)
id | reservation_id | date | time | room_id | rate
2 1 2014-18-04 13:00 1 9.99
3 1 2014-18-04 13:00 2 4.99
table payments - many payments for one reservation can be made
id | reservation_id | payment_amount | payment_type | guest_id
4 1 14.98 Cash 1
这是我的模特协会
//Reservation model
public $hasMany = array('ReservationDetail', 'Payment');
//ReservationDetail model
public $belongsTo = array('Reservation');
//Payment model
public $belongsTo = array('Reservation');
public $hasMany = array('ReservationDetail' => array('foreignKey' => 'reservation_id'));
我正在尝试做的是能够搜索付款,并且它将为该付款返回相应的Reservation和Reservation_details。因此,它将从reservation_details中获取共享相同reservation_id的所有记录。现在,保留已返回,但reserve_details返回为空
以下搜索从付款和预订返回信息,但从Reservation_details返回空数组。
$payment = $this->Payment->find('all',array(
'conditions' => array(
'Payment.guest_id' => '1'
)
));
我几乎可以肯定的是,它正在加入payments.id = payments.reservation_id上的reservation_details表,而不是payments.reservation_id = Reservation_details.reservation_id。当我手动将payments.id更改为1(reservation_id值)时,将返回reservation_details。
我相信我要实现的MySQL查询就像
SELECT reservations.*, reservation_details.*, payments.* from payments
INNER JOIN reservations on reservations.id = payments.reservation_id
INNER JOIN reservation_details on reservation_details.reservation_id = payments.reservation_ID
WHERE payments.guest_id = '1'
最佳答案
Payment.php
将可包含的行为添加为-
public $actsAs = array('Containable');
PaymentsController.php
$payments = $this->Payment->find('all', array(
'conditions' => array(
'Payment.guest_id' => '1'
),
'contain' => array(
'Reservation' => array(
'ReservationDetail'
)
)
));
debug($payments);
关于php - CakePHP的模型关联,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23164716/