2014-10-30 36 views

回答

8

爲了有一個就像一個Criteria::expr()->isNotNull('field')is not null可以使用

$criteria = Criteria::create(); 
$expr = $criteria::expr(); 
$collection->matching($criteria->where($expr->neq('field', null))); 

這個表達式生成器創建isNull以同樣的方式相匹配,而是通過改變比較運營商NEQ

return new Comparison($field, Comparison::EQ, new Value(null)); 

,然後由QueryExpressionVisitorBasicEntityPersister檢查,用於構建查詢。

對於Criteria::expr()->like()功能,Criteria::expr()->contains('property', 'value')等效於SQL property LIKE %value%。但它不允許更改爲value%%value,但pull request(從2.5.4開始)與已提議的startsWithendsWith方法已經與主合併 - 因此可以用2.5.5發佈。

對於Criteria::expr()->notLike()和其他LIKE變體不幸的是,Criteria使用的\Doctrine\Common\Collections\ExpressionBuilder不支持它們。

此外,如果比較操作符沒有定義(如CONTAINS,誤差由QueryExpressionVisitorBasicEntityPersister,這防止手動定義自己Comparison功能拋出。

http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-associations.html#filtering-collections


最好的替代方法是使用定製的存儲庫和DBAL查詢構建器的表達式,而不是代替期望的功能。

使用自定義實體存儲庫來過濾結果集將防止使用緩存的全表讀取您的集合並提高速度。

http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-objects.html#custom-repositories


一種替代是使用filter檢索對象的集合中的特定子集。

http://doctrine-orm.readthedocs.org/en/latest/reference/query-builder.html#the-expr-class

class MyEntity 
{ 
    public function getCollectionFieldNotLike($value) 
    { 
     return $this->getCollection()->filter(function($a) use ($value) { 
      return (false === stripos($a->getField(), $value)); 
     }); 
    } 

    public function getCollectionFieldLike($value) 
    { 
     return $this->getCollection()->filter(function($a) use ($value) { 
      return (false !== stripos($a->getField(), $value)); 
     }); 
    } 
} 
$repo->getCollectionFieldNotLike('value'); 
$repo->getCollectionFieldLike('value'); 

對於這兩種的上的存儲庫程序語法組合。

$criteria = Criteria::create(); 
$expr = $criteria::expr(); 
$criteria->where($expr->neq('field', null)); 
$collection = $entityManager->getRepository('app:MyEntity')->matching($criteria); 
$collectionNotLike = $collection->filter(function($a) { 
    return (false === strpos($a->getField(), 'value')); 
}); 

請記住,如上所述,這將迫使全表上收集閱讀,因爲它需要以能夠過濾結果檢索記錄。

+0

有沒有任何選項可以從$標準中獲得純SQL? Somethink like $ criteria-> toString() – 2016-12-14 10:14:35

+0

最好的辦法是使用'EntityPersister'。像這樣'echo $ em-> getUnitOfWork() - > getEntityPersister('app:MyEntity') - > getSelectSQL($ criteria);' – fyrye 2016-12-14 14:20:29

+0

要獲取參數值,請在條件對象上使用「expandCriteriaParameters」方法。像這樣:'list($ params,$ types)= $ em-> getUnitOfWork() - > getEntityPersister('app:MyEntity') - > expandCriteriaParameters($ criteria);'然後輸出你喜歡的參數'print_r($ PARAMS);' – fyrye 2016-12-14 14:34:09