CakePHP Conditions on deep model associations

2019-06-09 18:08发布

问题:

Using CakePHP 1.3, I have a Find statement with a condition on the 3rd level deep association: Hotel > Room > RoomType > name

I would like my Find statement to only return Hotels with RoomTypes that have the Name "Suite".

I believe the following code should work, but it does not, stating an SQL syntax error:

$this->Hotel->find('first', array(
    'contain' => array('Room' => array('RoomType')),
    'conditions' => array(
        'Hotel.Room.RoomType.name' => 'Suite' 
    ),
));

Please note that a Hotel will have many Rooms, but each Room will only have 1 RoomType

I have read about using the condition within the contain statement, but that only limits the RoomTypes returned, not the overall Hotels.

I have seen similar questions posted here, but I haven't found one that seems to solve this issue.

回答1:

You will need to manually create the joins & conditions as part of the query:

$this->Hotel->find('first', array(
    'contain'=>array(
        'Room'=>array(
            'RoomType'
        )
    ),
    'joins'=>array(
        array(
             'table'=>'rooms',
             'alias'=>'Room',
             'type'=>'inner',
             'conditions'=>array(
                  'Room.hotel_id'=>'Hotel.id'
             )
        ),
        array(
            'table'=>'room_types',
            'alias'=>'RoomType',
            'type'=>'inner',
            'conditions'=>array(
                'RoomType.id'=>'Room.room_type_id',
                'RoomType.name=>'Suit'
            )
        )
    )
);