Doctrine查询构建器 - 在多对多实体上运行查询

时间:2017-06-17 06:46:37

标签: php mysql symfony doctrine-orm doctrine

我正在使用查询构建器在我的应用程序中对多对多实体执行查询。问题是,doctrine查询构建器不使用“Many To Many”表来用于在两个实体之间存储数据。

当我在Entity中使用映射变量加入它们时,doctrine查询构建器会加入“父”表,这会导致错误的结果。

我不确定它为什么以及如何修复我的代码才能正常工作。

有人知道问题出在哪里吗?

这是我想要运行的查询(我想使用doctrine查询构建器运行的工作查询):

SELECT
  COUNT(1) AS total,
  gz.fleet_id AS type,
  MIN(bv.passenger_seats_number) AS min,
  MAX(bv.passenger_seats_number) AS max
FROM bus_vehicle AS bv

INNER JOIN company_stations AS cs
  ON cs.company_id = bv.company_id

INNER JOIN bus_vehicle_group_size AS gz
  ON (bv.passenger_seats_number BETWEEN gz.min AND gz.max)

WHERE cs.stations_id = 1

GROUP BY gz.fleet_id

学说查询:

$query = $repository->createQueryBuilder('bv')
        ->select('COUNT(1) as total, bt.type as busType, MIN(bv.passengerSeatsNumber) as minPersons, MAX(bv.passengerSeatsNumber) as maxPersons')
        ->join('bv.company', 'c')
        ->join('c.stations', 's')
        ->join('AppBundle:GroupSizeBusVehicle', 'gz', 'WITH', 'bv.passengerSeatsNumber >= gz.min AND bv.passengerSeatsNumber <= gz.max')
        ->join('gz.fleetType', 'bt')
        ->where('s.id = :stationId')
        ->setParameter('stationId', $stationId)
        ->groupBy('bv.busType')
        ->getQuery();
 dump ($query->getResult());

实体和映射:

公交车辆:

/**
 * @var \AppBundle\Entity\Company
 *
 * @ORM\ManyToOne(targetEntity="Company", inversedBy="busVehicle")
 * @ORM\JoinColumn(name="company_id", referencedColumnName="id")
 */
private $company;

公司:

/**
 * @var ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="Stations", inversedBy="company")
 */
private $stations;

/**
 * @ORM\OneToMany(targetEntity="BusVehicle", mappedBy="company")
 */

private $busVehicle;

监测站:

/**
 * @var ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="Company", mappedBy="stations")
 */
private $company;

从我的代码生成的学说查询:

SELECT 
  COUNT(1) AS sclr_0, 
  b0_.type AS type_1, 
  MIN(b1_.passenger_seats_number) AS sclr_2, 
  MAX(b1_.passenger_seats_number) AS sclr_3 
FROM 
  bus_vehicle b1_ 
  INNER JOIN company c2_ ON b1_.company_id = c2_.id 
  INNER JOIN company_stations c4_ ON c2_.id = c4_.company_id 
  INNER JOIN stations s3_ ON s3_.id = c4_.stations_id 
  INNER JOIN bus_vehicle_group_size b5_ ON (
    b1_.passenger_seats_number >= b5_.min 
    AND b1_.passenger_seats_number <= b5_.max
  ) 
  INNER JOIN bus_types b0_ ON b5_.fleet_id = b0_.id 
WHERE 
  s3_.id = ? 
GROUP BY 
  b1_.bus_type

修改

预期结果(来自第一次查询)

+-------+------+-----+-----+
| total | type | min | max |
+-------+------+-----+-----+
|     1 |    1 |  20 |  20 |
|     5 |    2 |  40 |  55 |
|     4 |    3 |  10 |  15 |
+-------+------+-----+-----+

我使用doctrine运行时得到的查询结果:

 0 => array:4 [▼
    "total" => "7"
    "busType" => "2"
    "minPersons" => "15"
    "maxPersons" => "55"
  ]
  1 => array:4 [▼
    "total" => "3"
    "busType" => "3"
    "minPersons" => "10"
    "maxPersons" => "15"

0 个答案:

没有答案