CakePHP的模型关联
我是CakePHP新手,在弄清楚如何建立模型关联方面有点困难 假设我有3个表:付款、预订和预订详细信息,包括以下数据CakePHP的模型关联,php,mysql,cakephp,Php,Mysql,Cakephp,我是CakePHP新手,在弄清楚如何建立模型关联方面有点困难 假设我有3个表:付款、预订和预订详细信息,包括以下数据 table reservations id | confirmation_number | guest_id 1 123 1 table reservation_details -a reservation can have multiple entries (multiple rooms) id |
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'));
我试图做的是能够搜索付款,它将返回相应的预订和该付款的预订详细信息。因此,它将从共享相同预订id的预订详细信息中获取任何记录。现在,将返回预订,但预订详细信息将返回空
以下搜索返回来自付款和预订的信息,但返回来自预订详细信息的空数组
$payment = $this->Payment->find('all',array(
'conditions' => array(
'Payment.guest_id' => '1'
)
));
我几乎可以肯定,它正在加入payments.id=payments.reservation\u id而不是payments.reservation\u id=reservation\u details.reservation\u id上的reservation\u details表。当我手动将payments.id更改为1(reservation\u id值)时,将返回reservation\u详细信息。
我相信我试图实现的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);