2014-04-19 245 views
0

我是CakePHP的新手,對於如何設置模型關聯有點麻煩。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_details。因此,它會從共享相同reservation_id的reservation_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。

我相信,我想實現將像

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' 

回答

0

Payment.php

的MySQL查詢

加中可容納的行爲原樣

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); 
+0

非常感謝!完美的作品! – user3476345