我遇到一个问题,我在Cakephp中有一个Find,旨在寻找在日历应用中忙碌的用户。但是,当我查看MYSQL查询时,它看起来不正确。
查找声明:
$result = $this->EventsUser->find('all',array('conditions'=>array(
'OR' =>array(
'AND' => array(
'Event.start >=' => $search_from,
'Event.end <=' => $search_to),
'AND' =>array(
'Event.end >' => $search_from,
'Event.end <=' => $search_to),
'AND' =>array(
'Event.start >=' => $search_from,
'Event.start <' => $search_to)
),
'User.is_resource'=>1
),
'group'=>array('EventsUser.user_id')
));
生成以下MYSQL查询:
SELECT `EventsUser`.`id`,
`EventsUser`.`event_id`,
`EventsUser`.`user_id`,
`EventsUser`.`status_id`,
`User`.`id`,
`User`.`role_id`,
`User`.`username`,
`User`.`password`,
`User`.`first_name`,
`User`.`last_name`,
`User`.`photo`,
`User`.`photo_dir`,
`User`.`email`,
`User`.`phone`,
`User`.`location`,
`User`.`cost_ctr`,
`User`.`color`,
`User`.`text_color`,
`User`.`token`,
`User`.`active`,
`User`.`is_resource`,
`User`.`category_id`,
`User`.`description`,
`User`.`created`,
`User`.`modified`,
`User`.`location_id`,
`User`.`mobile_number`,
`User`.`resource_fuel_card_pin`,
`User`.`resource_email_contact`,
`User`.`resource_office_hours`,
`User`.`resource_post_code`,
`User`.`resource_payroll_number`,
`User`.`line_manager_email`,
( Concat(`User`.`first_name`, ' ', `User`.`last_name`) ) AS `User__name`,
`Event`.`id`,
`Event`.`user_id`,
`Event`.`name`,
`Event`.`description`,
`Event`.`start`,
`Event`.`end`,
`Event`.`all_day`,
`Event`.`is_recurring`,
`Event`.`recurring_id`,
`Event`.`active`,
`Event`.`created`,
`Event`.`modified`,
`Event`.`owner`,
`Event`.`cost_cntr_id`,
`Event`.`txt_message`,
`Event`.`status_id`,
`Event`.`reason_for_hire_id`,
`Event`.`othersite_postcode`,
`Event`.`other_description`,
`Event`.`checksheet_id`,
`Event`.`declined_notes`,
`Event`.`hash`
FROM `car_pool`.`events_users` AS `EventsUser`
LEFT JOIN `car_pool`.`users` AS `User`
ON ( `EventsUser`.`user_id` = `User`.`id` )
LEFT JOIN `car_pool`.`events` AS `Event`
ON ( `EventsUser`.`event_id` = `Event`.`id` )
WHERE ( ( `Event`.`end` > '2015-06-07 13:01' )
AND ( `Event`.`end` <= '2015-06-12 13:01' ) )
AND `User`.`is_resource` = '1'
GROUP BY `EventsUser`.`user_id`
似乎缺少AND语句。当我从find中删除AND语句时,它总是在查找
上执行最后一个有人有任何想法吗?
答案 0 :(得分:1)
PHP 101,在关联数组中多次使用相同的键将覆盖以前的值。您多次使用'AND'
。只需删除'AND'
键,因为ANDing是默认行为。
答案 1 :(得分:1)
您的OR数组未正确定义。您创建了一个包含3个相同键的数组(即“AND”)
而不是:
'OR' =>array(
'AND' => array(
'Event.start >=' => $search_from,
'Event.end <=' => $search_to),
'AND' =>array(
'Event.end >' => $search_from,
'Event.end <=' => $search_to),
'AND' =>array(
'Event.start >=' => $search_from,
'Event.start <' => $search_to)
)
应该是这样的:
'OR' =>array(
array('AND' => array(
'Event.start >=' => $search_from,
'Event.end <=' => $search_to)),
array('AND' =>array(
'Event.end >' => $search_from,
'Event.end <=' => $search_to)),
array('AND' =>array(
'Event.start >=' => $search_from,
'Event.start <' => $search_to))
)