doctrine dql 不返回预期结果,而 MySQL 返回预期结果

doctrine dql not returning expected result where MySQL does

最后一个小时左右,我试图让下面的 MySQL 查询在 DQL 中工作,但是它没有返回预期结果,而是没有输出任何内容。

这是输出正确结果的MySQL查询。

MySQL:

SELECT vp.id FROM vehicle_photo AS vp
INNER JOIN vehicle AS v ON vp.vehicle_id = v.id AND vp.manualMaintenanceCheckedOn IS NULL AND vp.type_id = 1
LEFT JOIN vehicle_maintenance_history AS vmh ON vmh.vehicle_id = v.id AND vmh.source != 'kip' AND vmh.source != 'haan'
WHERE vmh.vehicle_id IS NULL
LIMIT 1;

DQL:

    $qb = $this->getDoctrine()->getEntityManager()->createQueryBuilder();
    $qb->select('vp.id')
        ->from('VaartlandIntranetBundle:VehiclePhoto', 'vp')
        ->innerJoin('vp.vehicle', 'v')
        ->leftJoin('v.vehicleMaintenanceHistory', 'vmh', \Doctrine\ORM\Query\Expr\Join::WITH, 'vmh.vehicle = v.id')
        ->where('vp.type = 1')
        ->andWhere('vp.manualMaintenanceCheckedOn is null')
        ->andWhere('vmh.source != :kip')
        ->andWhere('vmh.source != :haan')
        ->andWhere('vmh.vehicle IS NULL')
        ->setParameter('kip','kip')
        ->setParameter('haan','haan')
        ->setMaxResults(1);

    $ers = $qb->getQuery();
    $res = $qb->getQuery()->getResult();

据我们所知,vmh.source 有问题。当省略 "andWhere('vmh.source != :haan')" 和 "andWhere('vmh.source != :kip')" 时,DQL 查询会输出结果。但是,这些过滤器需要处于活动状态,因为两者都需要被过滤掉。

我希望你们知道如何修复结果集。

恕我直言,您的原始 SQL 与 Doctrine 生成的不同。我会尝试这样的事情:

$qb = $this->getDoctrine()->getEntityManager()->createQueryBuilder();
$qb->select('vp.id')
   ->from('VaartlandIntranetBundle:VehiclePhoto', 'vp')
   ->innerJoin('vp.vehicle', 'v')
   ->leftJoin(
       'v.vehicleMaintenanceHistory',
       'vmh',
       \Doctrine\ORM\Query\Expr\Join::WITH,
       $qb->expr()->andx(
           $qb->expr()->eq('vmh.vehicle', 'v.id'),
           $qb->expr()->neq('vmh.source', ':kip'),
           $qb->expr()->neq('vmh.source', ':haan')
       )
   )
   ->where('vp.type = 1')
   ->andWhere('vp.manualMaintenanceCheckedOn is null')
   ->andWhere('vmh.vehicle IS NULL')
   ->setParameter('kip', 'kip')
   ->setParameter('haan', 'haan')
   ->setMaxResults(1);

$ers = $qb->getQuery();
$res = $qb->getQuery()->getResult();

如果 haankip 动态参数将始终设置为 kiphaan 我会跳过赋值并将它们直接写在表达式中。

更多信息: