我有一个实体ID数组 - 我的任务是按照数组中指向的顺序获取实体。我发现“IN()”和“FIND_IN_SET”的组合可以解决这个问题。
我在QueryBuilder
的帮助下在存储库类中构建了一个查询:
$qb = $this->createQueryBuilder('v');
$qb
->select('v')
->addSelect("FIND_IN_SET('v.id', '$vehiclesStr')")
->andWhere('v.id IN(:vehicles)')
->setParameter('vehicles', $vehiclesArr)
;
return $qb->getQuery()->getResult();
如您所见,我使用beberlei/DoctrineExtensions中的“FIND_IN_SET”函数。它已根据issue进行了相应注册。
分别假设$vehiclesStr = '219,197,213,198';
$vehiclesArr = [219,197,213,198];
问题 - 订单未保存。我收到以下结果,其中车辆由ASC订购,例如197,198,213 ..:
通过Doctrine更新/构建SQL:
SELECT
v0_.vehicle_id AS vehicle_id_0,
v0_.number AS number_1,
v0_.cargo_movers AS cargo_movers_2,
v0_.vat AS vat_3,
v0_.bargain AS bargain_4,
v0_.cargo_search_radius AS cargo_search_radius_5,
v0_.adr AS adr_6,
v0_.tir AS tir_7,
v0_.passing_cargo AS passing_cargo_8,
v0_.description AS description_9,
v0_.created_at AS created_at_10,
v0_.updated_at AS updated_at_11,
v0_.transport_service_id AS transport_service_id_12,
v0_.vehicle_photo_id AS vehicle_photo_id_13,
v0_.vehicle_driver_id AS vehicle_driver_id_14,
v0_.vehicle_type_id AS vehicle_type_id_15,
v0_.vehicle_body_size_id AS vehicle_body_size_id_16,
v0_.vehicle_full_size_id AS vehicle_full_size_id_17,
v0_.vehicle_show_to_cargo_sender_id AS vehicle_show_to_cargo_sender_id_18,
v0_.vehicle_body_equipment_id AS vehicle_body_equipment_id_19,
v0_.vehicle_loading_type_id AS vehicle_loading_type_id_20,
v0_.vehicle_price_around_town_id AS vehicle_price_around_town_id_21,
v0_.vehicle_price_out_of_town_id AS vehicle_price_out_of_town_id_22
FROM
vehicle v0_
WHERE
v0_.vehicle_id IN (?)
ORDER BY
FIND_IN_SET('v.id', '219,188') ASC
Parameters: [[219, 188]]
答案 0 :(得分:0)
您根本没有使用ORDER BY
条款。在SELECT
条款中添加其他字段不会改变顺序。它会吗?
尝试使用orderBy
代替addSelect
。
$qb = $this->createQueryBuilder('v');
$qb
->select('v')
->andWhere('v.id IN(:vehicles)')
->setParameter('vehicles', $vehiclesArr)
->orderBy("FIND_IN_SET(v.id, '$vehiclesStr')", 'ASC');
;
return $qb->getQuery()->getResult();
假设$vehiclesStr
当然具有正确的价值。