2012-02-14 98 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')); 
}