简体   繁体   English

检查列是否已分组(QueryBuilder)

[英]Check if column was grouped (QueryBuilder)

I have the following query: 我有以下查询:

$qb
   ->select('z')
   ->where($qb->expr()->orX(
       $qb->expr()->like('z.city', ':czRequest')
   ))
   ->groupBy('z.city')
   ->setParameter('czRequest', $cz . '%');

With $cz = 'Ber' I get an array like this: 使用$cz = 'Ber'我得到一个像这样的数组:

array:3 [
 0 => array:4
  [ "id" => 12899 "country" => "DE" "city" => "Berlin" "code" => 14199 ]    
 1 => array:4
  [ "id" => 6483 "country" => "DE" "city" => "Berlingen" "code" => 54570 ]
 2 => array:4
 [ "id" => 8438 "country" => "DE" "city" => "Berlingerode" "code" => 37339 ]
]

Now 'Berlin' gives more than one (zip) 'code', in this example '14199' is obviously only the last one. 现在,“柏林”给出了多个(邮政编码)“代码”,在此示例中,“ 14199”显然只是最后一个。 'Berlingen' on the other hand only has one code. 另一方面,“ Berlingen”只有一个代码。

Is there any way to alter the query so that I have 'various' instead of '14199' but keep the others? 有什么办法可以更改查询,以使我拥有“多种”而不是“ 14199”,但保留其他? It does not have to be in the query itself, I think maybe a 'foreach' for the query (w/out the groupBy) and check for duplicate cities? 它不必一定在查询本身中,我想可能是查询的“ foreach”(不包括groupBy)并检查是否有重复的城市?

Any hint appreciated! 任何提示表示赞赏!

You should be able to achieve your need with that: 您应该能够满足您的需求:

$qb
  ->select('z, CASE WHEN (COUNT(z)) > 1 THEN \'various\' ELSE z.code END AS code2')
  ->where($qb->expr()->orX(
    $qb->expr()->like('z.city', ':czRequest')
  ))
  ->groupBy('z.city')
  ->setParameter('czRequest', $cz . '%');

You have to count your result (for a group by) and depending on the count, you can switch for a name or another. 您必须对结果进行计数(对于分组依据),并且根据计数,您可以切换一个名称或另一个名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM