我使用Doctrine\Common\Collections\Criteria::expr()
(不查詢生成器表達)。集合標準:: EXPR(),isNotNull和notLike
看來isNotNull()
和notLike()
運營商沒有在這個類中實現。
在這種情況下做isNotNull()
和notLike()
的最佳方法是什麼?
我使用Doctrine\Common\Collections\Criteria::expr()
(不查詢生成器表達)。集合標準:: EXPR(),isNotNull和notLike
看來isNotNull()
和notLike()
運營商沒有在這個類中實現。
在這種情況下做isNotNull()
和notLike()
的最佳方法是什麼?
爲了有一個就像一個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));
,然後由QueryExpressionVisitor
和BasicEntityPersister
檢查,用於構建查詢。
對於Criteria::expr()->like()
功能,Criteria::expr()->contains('property', 'value')
等效於SQL property LIKE %value%
。但它不允許更改爲value%
或%value
,但pull request(從2.5.4開始)與已提議的startsWith
和endsWith
方法已經與主合併 - 因此可以用2.5.5發佈。
對於Criteria::expr()->notLike()
和其他LIKE
變體不幸的是,Criteria使用的\Doctrine\Common\Collections\ExpressionBuilder
不支持它們。
此外,如果比較操作符沒有定義(如CONTAINS
),誤差由QueryExpressionVisitor
和BasicEntityPersister
,這防止手動定義自己Comparison
功能拋出。
最好的替代方法是使用定製的存儲庫和DBAL查詢構建器的表達式,而不是代替期望的功能。
使用自定義實體存儲庫來過濾結果集將防止使用緩存的全表讀取您的集合並提高速度。
一種替代是使用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'));
});
請記住,如上所述,這將迫使全表上收集閱讀,因爲它需要以能夠過濾結果檢索記錄。
有沒有任何選項可以從$標準中獲得純SQL? Somethink like $ criteria-> toString() – 2016-12-14 10:14:35
最好的辦法是使用'EntityPersister'。像這樣'echo $ em-> getUnitOfWork() - > getEntityPersister('app:MyEntity') - > getSelectSQL($ criteria);' – fyrye 2016-12-14 14:20:29
要獲取參數值,請在條件對象上使用「expandCriteriaParameters」方法。像這樣:'list($ params,$ types)= $ em-> getUnitOfWork() - > getEntityPersister('app:MyEntity') - > expandCriteriaParameters($ criteria);'然後輸出你喜歡的參數'print_r($ PARAMS);' – fyrye 2016-12-14 14:34:09