Symfony 2 Doctrine find by ordered array of id
Asked Answered
T

2

25

I'm looking for a way to use Doctrine in Symfony 2 to find items using an ordered array of id.

I have a Card entity with id (primary key) and title.

I have a ListCards entity with id (primary key) and a listCards (an array of ids encoded : ["16", "2", "84"])

I first fetch the list and then I need to find cards with those ids in that order.

I try something like :

$idsArray = ["16", "2", "84"];
$cardRepository->findby($idsArray);

but Doctrine fetch my cards in ASC order.

ORDER BY FIEDS sql method doesn't seem to be supported by doctrine.

Is there any simple solution for that kind of sorting ?

Thank you (and sorry for my bad english).

Tocology answered 17/2, 2015 at 14:31 Comment(0)
F
36

You can use it like:

$cardRepository->findBy( array('id' => $idsArray), array('id' => 'DESC') );

Check also the official doctrine documentation for more details on how to use ordering, limit and offset as second to fourth parameters in the findBy method.

Flurried answered 18/2, 2015 at 8:4 Comment(3)
Thank for your answer but i don't want a DESC order but my array order. And I don't find any parameters in ‘findBy‘ method that allow this kind of feature.Tocology
You can send array $idsArray and array with entities to twig. Then you can use loop for $idsArray.Flurried
I was not able to do this directly in Doctrine, but here's a way to get a specified ordering (4, 7, 1, 6 in this example) from Postgres: select * from my_table join unnest('{4,7,1,6}'::varchar[]) with ordinality o(my_id, ord) on o.my_id = my_table.my_id order by ord asc;Pregnancy
F
0

You can create a helper table, where you store ordered group elements, having the following data: (group_id, card_id, order)

You search by group_id, order by order and read the card_id.

Fahland answered 17/2, 2015 at 14:36 Comment(1)
Thank you. I will try something like this. Too bad there is no sort parameter other than ASC ou DESC in findBy doctrine method.Tocology

© 2022 - 2024 — McMap. All rights reserved.