php - Symfony Query Builder 如何获取最后分组的记录
问题描述
我有一个名为“位置”的实体,其中包含以下字段:
- id(自动递增)
- 车辆(“车辆”表的外键)
- 纬度
- 液化天然气
- 速度
我需要使用学说查询生成器按车辆分组的最后一个位置(带有最后一个 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;
}
谢谢你的帮助。
解决方案
要从每个车辆的位置实体中选择最新记录,您可以使用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');
}
查看类似的解决方案
推荐阅读
- python - 在 python 中输入可变参数
- ios - iOS 应用的部署目标
- sql - 使用 SQL,是否可以使用引用该表的外键从不同的表(使用存储过程)中检索字段?
- css - 引导下拉菜单问题
- python - 同一函数中的 UnboundLocalError - Python
- python - 带有结构列的 Pyspark Parquet
- android - 在 ubuntu 18.04 中安装颤振时出错:“Android 许可证状态未知”
- android - 找不到 mainActivity 文件
- jquery - 如何在jquery中将数据序列化()和新的formData相互结合
- c++ - 如何在mac上的Cmake中链接libavformat?