[英]Use advanced select in doctrine2/ symfony2
我需要在我的職責字段(文本類型)中找到一種獲取$ text出現次數的方法。
我試圖把這樣的查詢:
select("cv.id, (CHAR_LENGTH(cve.responsibilities)
-
CHAR_LENGTH(REPLACE(LOWER(cve.responsibilities),LOWER(" . $text. "),'')))/CHAR_LENGTH(" . $text . ") AS count")
在symfony2中進入我的queryBuilder。
我知道這種查詢離理想還很遙遠,但是我被迫這樣做。 我在functionNode中添加了replace和regexp函數,但主要問題是選擇字段。 這是我嘗試過的(為了清楚起見,我拆分了代碼以獲取額外的變量):
$qb = $this->createQueryBuilder('a');
$expr = $qb->select()->expr();
$diff1 = $expr->length("b.description");
$diff2 = $expr->length("replace( " . $expr->lower('b.description') . ", " . $expr->lower(':text') .", '')");
$counter = $expr->diff($diff1, $diff2);
$denominator = $expr->length(':text');
$qb->select('a.id,' . $expr->quot(':counter', ':denominator') . 'as count')
->join('a.additional', 'b')
->where('REGEXP ("[[:<:]]' . $text . '[[:>:]]", b.description)')
->andWhere('a.id IN (:Ids)')
->setParameters([
'text' => $text,
'counter' => $counter,
'denominator' => $denominator,
'Ids' => $Ids
]);
好的,它適用於:
$qb->select('a.id id,' . $expr->quot($counter, $denominator . ' field'))
->join('a.additional', 'b')
->where("regexp('[[:<:]]" . $text . "[[:>:]]', b.description) != false")
->andWhere('a.id IN (:Ids)')
->setParameter('text', $text );
if(!empty($Ids)){
$qb->andWhere('a.id IN (:Ids)')
->setParameter('Ids', $Ids);
}
使用SQL查詢大數據總是比使用DQL更好,嘗試這樣的事情:
LENGTH( cve.responsibilities) - LENGTH(REPLACE(cve.responsibilities, '. $text.', '')) AS counts
這應該使您可以算出現場職責中的次數或發生的次數。
您可以將其添加到您的存儲庫類中,調用並獲得我在我這邊測試過的結果
public function getTested()
{
return $this->createQueryBuilder('cve')
->select("cve.id, (LENGTH(cve.responsibilities) - LENGTH(REPLACE(cve.responsibilities, '". $text ."','')))/LENGTH('". $text ."')")
->getQuery()->getArrayResult();
}
在這里REPLACE函數按照鏈接原則查詢進行操作-忽略空格
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.