CakePHP Conditions on deep model associations

我的梦境 提交于 2019-12-23 05:35:07

问题


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'
            )
        )
    )
);


来源:https://stackoverflow.com/questions/8249978/cakephp-conditions-on-deep-model-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!