2012-02-03 115 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();