2012-02-03 120 views
1
FIRST: 
id | name 
1 | sss 
2 | ddd 
5 | fff 

    $q = Doctrine_Query::create() 
    ->from('First a'); 

    return $q->execute(); 

SECOND: 
id | first_id | name 
.... 


    $two = Doctrine_Query::create() 
    ->from('Second a') 
    ->whereInNot(first_id, $q) // ??????? 
    ; 

    return $two->execute(); 

如何從表中獲取表中第一個沒有first_id的所有數據?Where In Not - doctrine

+0

與您的代碼的問題包括:第一查詢返回一個Doctrine_Collection(就像Doctrine_Records的列表),它不是一個數組,您可以將其添加到第二個查詢中。此外,您需要的方法是「whereNotIn()」而不是「whereInNot()」。在我的答案中,我提供了兩個示例來說明如何編寫代碼,具體取決於您是否確實需要知道first_ids。 – ybull 2012-02-04 20:32:15

回答

2

方法一(類似於你的示例代碼):

// Retrieve ONLY the id, and use hydration mode that produces a simple array of results. 
$first_ids = Doctrine_Query::create() 
    ->select('f.id') 
    ->from('First f') 
    ->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR); 

$two = Doctrine_Query::create() 
    ->from('Second s') 
    ->whereNotIn('first_id', $first_ids); 
return $two->execute(); 

另一種方法來獲得同樣的結果在一個單一的複合查詢:

$two = Doctrine_Query::create() 
    ->from('Second s') 
    ->where('first_id NOT IN (SELECT id FROM First)'); 
return $two->execute();