24

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).

implmentor
  • 1,386
  • 4
  • 21
  • 32
Benjamin
  • 241
  • 1
  • 2
  • 4

2 Answers2

35

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.

Community
  • 1
  • 1
Max Lipsky
  • 1,774
  • 1
  • 18
  • 29
  • 1
    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. – Benjamin Feb 19 '15 at 11:03
  • You can send array $idsArray and array with entities to twig. Then you can use loop for $idsArray. – Max Lipsky Feb 20 '15 at 09:32
  • 2
    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;``` – Derek Kurth Sep 04 '19 at 20:38
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.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 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. – Benjamin Feb 19 '15 at 11:05