2012-09-02 121 views
1

例如,我有一個Store模型,其字段爲H和toH,我想從數據庫中檢索在給定小時(@t)打開的存儲。CakePHP複雜查找條件

SQL查詢應該是這樣的

select * 
from store 
where 
(fromH < toH and @t between fromH and toH) or 
(fromH > toH and 
    (@t between fromH and 24 OR 
    (@t between 1 and toH) 
) 

如何實現CakePHP的這個查詢,怎麼會條件陣列看?我想做蛋糕風格。

回答

1

答案是非常接近的解決方案,但作爲或國家的規則,每一個都必須各自爲陣,因爲他們的關鍵價值是相同的。如果你

print_r($conditions); 

你會發現你的一些規則丟失。

我認爲以下解決方案將爲您工作。

$conditions = array(
    'conditions' => array(
     'OR' => array(
      array(
       'AND' => array(
        'fromH <' => 'toH', 
        @t.' BETWEEN ? AND ?' => array('fromH','toH') 
       ) 
      ), 
      array(
       'AND' => array(
        'fromH >' => 'toH', 
        'OR' => array(
         @t.' BETWEEN ? AND ?' => array('fromH','24'), 
         @t.' BETWEEN ? AND ?' => array('1','toH') 
        ) 
       ) 
      ) 
     ) 
    ) 
); 

$this->Strore->find('all',$conditions); 
+0

當我嘗試運行此查詢時,我得到以下錯誤:錯誤:SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'15' - 「15」是@t – user1399007

+0

Can你請在這裏發佈你的條件查詢代碼? – dirtyhandsphp

1

你可以用以下的CakePHP相當於選擇查詢嘗試:通過@Arun耆那教給

<?php $this->Store->find('all', array(
    'conditions' => array(
     'OR' => array(
      'AND' => array(
       'fromH < ' => 'toH', 
       $t.' BETWEEN ? AND ?' => array('fromH', 'toH') 
      ) 
     ), 
    'AND' => array(
      'fromH > ' => 'toH', 
      'OR' => array(
       $t.' BETWEEN ? AND ?' => array('fromH', '24'), 
       $t.' BETWEEN ? AND ?' => array('1', 'toH') 
      ) 
     ), 
    ) 
)); 
+0

Thanks @bancer for code formatting。 :) –

+1

也可能想修復之間的雙重。 – tigrang

+0

謝謝,將嘗試 – user1399007