php - 在多对多表上使用左连接时,Symfony 3 返回错误的查询结果

标签 php mysql symfony doctrine

我有两个实体和一个多对多表。我想要实现的是获取多对多表中不存在的记录。

在我的场景中,我有公交车实体和车站(旅行目的地)价格。用户可以定义每个车站的价格并选择适用于该路线(或车站)的巴士车辆。我想要获取未选择所需车站(或路线)的公交车

这是公交车车辆(缩写版)实体:

/**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="StationStandardPrice", mappedBy="busVehicles", cascade={"persist"})
     */

    private $busVehicleGroup;

站实体(短接):

/**
     *  Many station can have many bus vehicles
     *
     * @ORM\ManyToMany(targetEntity="BusVehicle", inversedBy="busVehicleGroup")
     * @ORM\JoinTable(name="standard_station_price_bus_groups",
     *     joinColumns={@ORM\JoinColumn(name="station_standard_price_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="bus_vehicle_id", referencedColumnName="id")}
     * )
     **/

    private $busVehicles;

Controller :

 $busVehicles = $em->getRepository("AppBundle:BusVehicle")
                ->createQueryBuilder('bv')
                ->addSelect('sp')
                ->leftJoin('bv.busVehicleGroup', 'sp')
                ->where('bv.company = :company')
                ->andWhere ('sp.id IS NULL')//When I remove this line I get buses that is already selected
                ->andWhere('sp.departureStation = :departureStation')
                ->andWhere('sp.destinationStation = :destinationStation')
                ->andWhere('bv.passengerSeatsNumber BETWEEN :minPassenger AND :maxPassenger')
                ->setParameter('company', $company)
                ->setParameter('departureStation', $request->request->get('departureStation'))
                ->setParameter('destinationStation', $request->request->get('destinationStation'))
                ->setParameter('minPassenger', $request->request->get('minPassenger'))
                ->setParameter('maxPassenger', $request->request->get('maxPassenger'))
                ->getQuery()
                ->getResult();



            //$redirectUrl = $request->request->get('redirectUrl');
            dump ($busVehicles);

            return $this->json(['busVehicles' => $busVehicles]);

最佳答案

连接表无法使用 DQL(或 QueryBuilder)进行查询,因为它不是实体,只能使用 sql 进行此类查询。然后,为了简化查询,我的建议是获取已选择的总线,然后在总线表中查找未包含在该列表中的所有总线。

修改您的第一个查询以获取所有选定公交车 ID 的列表,然后获取与这些 ID 不匹配的公交车列表。

$em->getRepository("AppBundle:BusVehicle")
           ->createQueryBuilder('bv')
           ->where($qb->expr()->notIn('bv.id', $selectedBusIds))
           ->getQuery()
           ->getResult();

关于php - 在多对多表上使用左连接时,Symfony 3 返回错误的查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43844796/

相关文章:

php - Laravel 代客总是询问密码

mysql - 检索相互覆盖的唯一用户的查询

mysql - 需要帮助构建带有 join 和 where 的多对多关系的 sql 查询

php - 计算 imagefk 等于的记录总数?在交响乐中

symfony - 依赖不存在的服务 "doctrine.orm.default_entity_manager"

php - SQL语句的计算速度

php - 导航子菜单项未出现在 iframe 中

mysql - 在联合查询中按日期排序

Mysql 读锁 SELECT FOR UPDATE

php - 如何在 AWS EC2 服务器中编写 cron 作业