查询构建器“ addSelect”会影响“ addOrderBy”

时间:2019-06-18 05:42:57

标签: symfony doctrine-orm doctrine query-builder doctrine-query

我有Symfony 4宽度原则,两个实体/表具有关系装置(一个)-图片(许多)。两个表都具有名称为“ order”的列。 我正在(急切地)加载所有灯具及其图片。我正在尝试仅按根实体对查询结果进行排序。

不使用“ addSelect”功能时,它会按预期工作。

$qb = $repository->createQueryBuilder('fixture');
$qb->innerJoin('fixture.pictures', 'pictures');
$qb->addOrderBy('fixture.order', 'ASC');

结果是:

SELECT f0_.name AS name_0, f0_.color AS color_1, f0_.`order` AS order_2, f0_.id AS id_3, f0_.valid_from AS valid_from_4, f0_.valid_to AS valid_to_5, f0_.disabled AS disabled_6 FROM fixture f0_ INNER JOIN fixture_picture f1_ ON f0_.id = f1_.fixture_id ORDER BY f0_.`order` ASC

但是当我将其更改为

$qb = $repository->createQueryBuilder('fixture');
$qb->innerJoin('fixture.pictures', 'pictures');
$qb->addSelect('pictures');  //eager loading
$qb->addOrderBy('fixture.order', 'ASC');

我得到:

SELECT f0_.name AS name_0, f0_.color AS color_1, f0_.`order` AS order_2, f0_.id AS id_3, f0_.valid_from AS valid_from_4, f0_.valid_to AS valid_to_5, f0_.disabled AS disabled_6, f1_.id AS id_7, f1_.`order` AS order_8, f1_.file_name AS file_name_9, f1_.file_path AS file_path_10, f1_.fixture_id AS fixture_id_11 FROM fixture f0_ INNER JOIN fixture_picture f1_ ON f0_.id = f1_.fixture_id ORDER BY f0_.`order` ASC, f1_.`order` ASC

我真的不确定为什么会有“ f1 _。order ASC”。我也尝试过

$qb->addOrderBy('pictures.order', 'ASC');

并且在这种情况下,它可以正常工作(仅按图片排序)。

TL; DR; 当使用“ $ qb-> addSelect('pictures');”时在查询生成器中,即使只对根实体进行排序,SQL查询中也会添加“,f1 _。order ASC”的额外顺序。当不使用“ addSelect”或按联接表'pictures.order'对查询进行排序时,它可以正常工作

1 个答案:

答案 0 :(得分:0)

@ehymel是正确的。我在实体“ Fixture”中使用了@ORM \ OrderBy批注,但忘记了。