gpt4 book ai didi

php - CakePHP 的模型关联

转载 作者:行者123 更新时间:2023-11-30 00:21:55 24 4
gpt4 key购买 nike

我是 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_details 中获取共享相同reservation_id 的所有记录。现在预订已返回,但reservation_details返回为空

以下搜索返回来自付款和预订的信息,但来自reservation_details 的空数组。

$payment = $this->Payment->find('all',array(
'conditions' => array(
'Payment.guest_id' => '1'
)
));

我几乎肯定它是在 payment.id = payment.reservation_id 而不是 payment.reservation_id =servation_details.reservation_id 上加入reservation_details表。当我手动将 payment.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'

最佳答案

付款.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com