2013-04-05 79 views
0

我正在使用cakephp 2.3.0。總結 - 在我的控制器中,我有一個查詢返回一個或多個id值。然後,我想在下一個查詢中使用這些id值,並使用SQL IN關鍵字。我從概念上知道我想完成什麼。我認爲我在CakePHP中以正確的方式執行此操作,但我可能是錯的。我只是不確定編碼塊是否動態構建我的IN子句。動態地在IN關鍵字中創建一個SQL語句

這裏是我的控制器我的代碼片段:

$this->set('userIDs', $this->Activity->ActivitiesOfInterest->find('all', 
       array (
        'conditions' => array ('ActivitiesOfInterest.activities_id' => $id), 
        'fields' => array ('ActivitiesOfInterest.user_id')))); 

上面的代碼是好的,因爲我獲得的價值或我所期望的值。在下面的代碼中,我對這塊數組(3,4)進行了硬編碼,這相當於SQL IN關鍵字。值3,4將存儲在userIDs數組中。但是,這是我不確定如何從上面的代碼中的數組動態構建3和4的值。當然,3和4並不總是值,因爲它只取決於數據庫中的內容。我想我需要遍歷數組並建立我的id列表。我對CakePHP還是有點新鮮,我猜這對於有經驗的人來說是一個簡單的答案。

而且,我實際上是想根據我的使用情況執行deleteAll操作。

$this->Activity->ActivitiesOfInterest->deleteAll(
        array('ActivitiesOfInterest.user_id' => array(3, 4)), false); 

謝謝,非常感謝。

回答

-1

您不需要使用$this->set(),除非您在視圖中需要這些用戶ID; Hash::extract()在這裏可能會有幫助。

// Find the user-ids 
$result = $this->Activity->ActivitiesOfInterest->find('all', array (
    'conditions' => array (
     'ActivitiesOfInterest.activities_id' => $id 
    ), 
    'fields' => array (
     'ActivitiesOfInterest.user_id' 
    ) 
)); 

if ($result) { 
    // 'extract' just the user-ids from the results 
    $userIds = Hash::extract($result, '{n}.ActivitiesOfInterest.user_id'); 

    $this->Activity->ActivitiesOfInterest->deleteAll(
     array(
      'ActivitiesOfInterest.user_id' => $userIds 
     ), 
     false 
    ); 
} 
+0

這樣做的伎倆。謝謝您的幫助! – Kevin 2013-04-05 23:27:56

+0

很高興能幫到你! – thaJeztah 2013-04-05 23:30:49

0

您也可以通過使用子查詢deleteALL查詢來做到這一點。

$conditionsSubQuery['ActivitiesOfInterest.activities_id'] = $id; 
$db = $this->Financial->getDataSource(); 
     $subQuery = $db->buildStatement(
       array(
      'fields' => array('ActivitiesOfInterest.user_id'), 
      'table' => $db->fullTableName($this->Activity->ActivitiesOfInterest), 
      'alias' => 'ActivitiesOfInterest', 
      'offset' => null, 
      'joins' => array(), 
      'conditions' => $conditionsSubQuery, 
      'order' => null, 
      'group' => null 
       ),$this->Activity->ActivitiesOfInterest 
     ); 
     $subQuery = ' ActivitiesOfInterest.user_id IN (' . $subQuery . ')' ; 
     $subQueryExpression = $db->expression($subQuery); 

     $conditions[] = $subQueryExpression; 
     $result = $this->Activity->ActivitiesOfInterest->deleteAll(compact('conditions'));