CakePHP的模型关联 [英] Model associations for CakePHP
问题描述
我是CakePHP的新手,在弄清楚如何建立模型关联时遇到了一些麻烦。
I'm new to CakePHP and having a bit of trouble figuring out how to set up model associations.
说我有3个表:付款,预订和Reservation_details及其以下数据
Say I have 3 tables: payments, reservations and reservation_details with the following data
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返回为空
What I'm trying to do is be able to search for a payment and it would return the corresponding reservation and reservation_details for that payment. So it would grab any records from reservation_details that share the same reservation_id. Right now the reservation is returned, but the reservation_details is returned empty
以下搜索从付款和预订中返回信息,但从Reservation_details返回空数组。
The following search returns information from payments and reservations, but an empty array from 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查询
I believe the MySQL query that I'm trying to achieve would be something like
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
将可包含的行为添加为-
Payment.php
add containable behavior as-
public $actsAs = array('Containable');
PaymentsController.php
PaymentsController.php
$payments = $this->Payment->find('all', array(
'conditions' => array(
'Payment.guest_id' => '1'
),
'contain' => array(
'Reservation' => array(
'ReservationDetail'
)
)
));
debug($payments);
这篇关于CakePHP的模型关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!