首页 > 解决方案 > Symfony Query Builder 如何获取最后分组的记录

问题描述

我有一个名为“位置”的实体,其中包含以下字段:

我需要使用学说查询生成器按车辆分组的最后一个位置(带有最后一个 id)。

这是我的功能:

// Find locations
public function findLocations($idFleet, $select, $from, $to)
{
    $qb = $this->createQueryBuilder('l')
    ->innerJoin('l.vehicle', 'v')
    ->where('v.fleet = :fleet')
    ->setParameter('fleet', $idFleet)
    ->andWhere('v.gps = :gps')
    ->setParameter('gps', true);

    // Last locations
    if ( $select == "last"){
        $qb->groupBy('l.vehicle')
            ->orderBy('l.id', 'ASC');            
    }
    // else Interval locations
    else if ( $select == "interval"){
        if( $from != ""){
            $from = (new \DateTime())->setTimestamp($from);
            $qb->andWhere('l.time >= :from')
            ->setParameter('from', $from);
        }
        if( $to != ""){
            $to = (new \DateTime())->setTimestamp($to);
            $qb->andWhere('l.time <= :to')
            ->setParameter('to', $to);
        }
    }
    $locations = $qb->getQuery()->getResult();
    return $locations;   
}

谢谢你的帮助。

标签: phpsqlsymfonydoctrinegreatest-n-per-group

解决方案


要从每个车辆的位置实体中选择最新记录,您可以使用WITH子句和在 where 子句中检查空值的附加连接条件对位置实体进行自左连接,每个位置具有最高 id 的行对自连接行将具有空值.

// Last locations
if ( $select == "last"){
    $qb
    ->leftJoin( 'YourBundle\Entity\Location', 'l1', 'WITH', 'l.vehicle = l1.vehicle AND l.id < l1.id' )
    ->andWhere('l1.vehicle IS NULL' )
    ->orderBy('l.id', 'ASC');            

}

查看类似的解决方案


推荐阅读