创建复杂的SQL语句 - CakePHP

时间:2013-02-04 12:02:26

标签: php mysql cakephp-2.0

我正在尝试查找用户输入的日期是否与数据库上的任何日期重叠。

我已经关闭了SQL语句(可能需要一些调整,会测试)但我正在努力将它正确地转换为cakePHP。

我有什么

$result = $this->find('all', array(
    'conditions' => array(
        'OR' => array(
            'AND' => array(
                array('BoardroomBooking.start_time >=' => $this->data['BoardroomBooking']['start_time']),
                array('BoardroomBooking.start_time <' => $this->data['BoardroomBooking']['start_time'])
            ),
            'AND' => array(
                array('BoardroomBooking.start_time <=' => $this->data['BoardroomBooking']['start_time']),
                array('BoardroomBooking.start_time >' => $this->data['BoardroomBooking']['end_time'])
            )
        )
    )
));

它创造了什么

SQL Query: SELECT `BoardroomBooking`.`id`, `BoardroomBooking`.`name`,
`BoardroomBooking`.`boardroom_id`, `BoardroomBooking`.`date`, 
`BoardroomBooking`.`start_time`, `BoardroomBooking`.`end_time`, 
`BoardroomBooking`.`notes`, `BoardroomBooking`.`recurrence_id`, 
`BoardroomBooking`.`created`, `BoardroomBooking`.`modified`, `Boardroom`.`id`, 
`Boardroom`.`name`, `Boardroom`.`created`, `Boardroom`.`modified` FROM 
`intraweb_db`.`boardroom_bookings` AS `BoardroomBooking` LEFT JOIN 
`intraweb_db`.`boardrooms` AS `Boardroom` ON (`BoardroomBooking`.`boardroom_id`
 = `Boardroom`.`id`) WHERE ((`BoardroomBooking`.`start_time` <= '12:55:00') AND 
(`BoardroomBooking`.`start_time` > '13:00:00'))

我想要什么

SQL Query: SELECT `BoardroomBooking`.`id`, `BoardroomBooking`.`name`,
`BoardroomBooking`.`boardroom_id`, `BoardroomBooking`.`date`, 
`BoardroomBooking`.`start_time`, `BoardroomBooking`.`end_time`, 
`BoardroomBooking`.`notes`, `BoardroomBooking`.`recurrence_id`, 
`BoardroomBooking`.`created`, `BoardroomBooking`.`modified`, `Boardroom`.`id`, 
`Boardroom`.`name`, `Boardroom`.`created`, `Boardroom`.`modified` FROM 
`intraweb_db`.`boardroom_bookings` AS `BoardroomBooking` LEFT JOIN 
`intraweb_db`.`boardrooms` AS `Boardroom` ON (`BoardroomBooking`.`boardroom_id`
 = `Boardroom`.`id`) WHERE (`BoardroomBooking`.`start_time` >= '12:55:00' AND 
`BoardroomBooking`.`start_time` < '12:55:00') OR (`BoardroomBooking`.`start_time`
 <= '12:55:00') AND (`BoardroomBooking`.`start_time` > '13:00:00'))

我已经阅读了如何retrieve data的文档,但是因为我的生活无法按照我想要的方式工作。

1 个答案:

答案 0 :(得分:1)

现在,我可能不正确,但我相信你的问题在你的数组声明中:

  array(
    'AND' => array(
      ...
    ),
    'AND' => array(
      ...
    )
  )

就PHP而言,你刚刚在数组中声明了一个“AND”键,然后重新分配它。根据{{​​3}},您需要在单独的数组中声明相同的字段:

'OR' => array(
  array('AND' => array (...)),
  array('AND' => array (...))
)

这可以防止查询将您的两个条件视为相同的事情并覆盖条目。