Symfony3 QueryBuilder使用Subquery进行更新

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Symfony3 QueryBuilder使用Subquery进行更新相关的知识,希望对你有一定的参考价值。

我尝试过以下内容:

 $subQuery = $this->createQueryBuilder('teachingEvent')->select('teachingEvent.id')
        ->leftJoin('teachingEvent.timeTableEntry', 'timeTableEntry')
        ->leftJoin('timeTableEntry.course', 'course')
        ->where('course.school = :school' )
        ->andWhere('teachingEvent.date >= :fromDate')
        ->andWhere('teachingEvent.date <= :toDate')
        ->setParameters(array(':fromDate' => $from, ':toDate' => $to, ':school' => $school))
        ->getDQL();


    $query = $this->createQueryBuilder('teachingEvent')
        ->update()
        ->set('teachingEvent.schoolFreeDate', ':schoolFreeDate')
        ->where('teachingEvent.id IN ' . $subQuery)
        ->getQuery();

    return $query->getResult();

当我转出子查询时,我得到了这个:

“SELECT teachingEvent.id FROM AppBundle Entity TeachingEvent teachingEvent LEFT JOIN teachingEvent.timeTableEntry timeTableEntry LEFT JOIN timeTableEntry.course course WHERE course.school =:school AND teachingEvent.date> =:fromDate AND teachingEvent.date <=:toDate

对我来说,似乎现在应该工作 - 但我收到以下错误消息

[语法错误]第0行,第136栏:错误:预期的文字,得到'teachingEvent'

如果有人能找到错误会很好。

感谢你!

新年快乐 ;)!

答案

您也可以通过首先从第一个查询构建器获取对象然后执行所需的更新来执行相同的操作

$teachingEvents =  $this->createQueryBuilder('teachingEvent')
                        ->select('teachingEvent')
                        ->leftJoin('teachingEvent.timeTableEntry', 'timeTableEntry')
                        ->leftJoin('timeTableEntry.course', 'course')
                        ->where('course.school = :school' )
                        ->andWhere('teachingEvent.date >= :fromDate')
                        ->andWhere('teachingEvent.date <= :toDate')
                        ->setParameters(array(':fromDate' => $from, ':toDate' => $to, ':school' => $school))
                        ->getQuery()
                        ->getResult();

foreach($teachingEvents as $teachingEvent){
    $teachingEvents->setSchoolFreeDate($someDate);
    $em->persist($teachingEvents);
    /* $em->flush(); flush here or after loop */
}

$em->flush();

以上是关于Symfony3 QueryBuilder使用Subquery进行更新的主要内容,如果未能解决你的问题,请参考以下文章

TypeOrm - NestJS 使用 queryBuilder

Symfony2,如何使用 KnpPaginatorBundle 和 QueryBuilder 传递参数排序和方向

如何使用 Cassandra 中的 QueryBuilder 定义具有 2 个条件的 Where 查询?

在 Doctrine DBAL 中重用 QueryBuilder

在 QueryBuilder 中使用动态输入时出现意外结果

在 TypeORM 中使用 QueryBuilder 与 Repository 都有哪些不同的用例? [关闭]