2012-02-14 96 views
1

有我计算(我试图从昨天把所有“行动项目”,并将其储存在“paste_due”以下,并为今天的所有行动项目,并把它们存储在一个更好的办法“今天”) - 这是我的“代理”控制器(代理“的hasMany” ActionItem和ActionItem“属于关联”剂)的内部:CakePHP的:日期范围

public function planner() { 

    $yesterday = date("Y-m-d 23:59:59", strtotime("yesterday")); 
    $conditions = array('ActionItem.due <' => $yesterday, 'ActionItem.agent_id' => '1'); 
    $this->set('past_due', $this->Agent->ActionItem->find('all', array('conditions' => $conditions))); 

    $today = date("Y-m-d 00:00:00", strtotime("today")); 
    $today_end = date("Y-m-d 23:59:59", strtotime("today")); 
    $conditions = array('ActionItem.due >' => $today, 'ActionItem.due <' => $today_end, 'ActionItem.agent_id' => '1'); 
    $this->set('today', $this->Agent->ActionItem->find('all', array('conditions' => $conditions))); 
} 

上述工作,但我不知道这是否是最好的的方式去我..

回答

0

会有余地有所改善(虽然如你所说,目前的代码应该工作,所以它只是我的一些想法)。

首先,如果你只是要检查几次都是00:00:0023:59:59,完全放弃的时候,只是用DATE场,而不是DATETIME场。它使检查更容易,因为您不必担心时间。 (如果时间对于您的应用程序的其他部分必要的,那么下面的示例代码应作相应调整。)

而且我会使用PHP的DateTime功能,而不是date()strtotime(),主要是因为它几乎是每当我使用日期/时间数据时,这是我的习惯。这是因为日期时间增加了很多的可能性和灵活性,以您的日期和时间数据没有太多的麻烦。像这样的东西是什么我可能会去:

public function planner() { 

    // Set the DateTime object (defaults to current date/time) 
    $today = new DateTime(); 

    // Overdue actions (everything older than today) 
    $overdue = $this->Agent->ActionItem->find('all', array(
     'conditions' => array(
      // Check due against a 'Y-m-d' formatted date of today. 
      'ActionItem.due <' => $today->format('Y-m-d'), 
      'ActionItem.agent_id' => '1' 
     ) 
    )); 

    // Actions due today (or in the future) 
    $due = $this->Agent->ActionItem->find('all', array(
     'conditions' => array(
      // Check due against a 'Y-m-d' formatted date of today. 
      'ActionItem.due >=' => $today->format('Y-m-d'), 
      'ActionItem.agent_id' => '1' 
     ) 
    )); 

    // Set the items 
    $this->set(compact('overdue', 'due')); 
}