0

I have a doctrine collection with several objects. Each object has a field called control. The field holds a number.

How do I return a set of objects from the collection, matching and arranged in control order of a given array (in this case, [1616, 1617, 518])?

The idea is that, you have many records (say 20+) from the database and you are holding them in a Doctrine Collection. In the collection, each record is in the form of an Entity. Each of the entities has a field called control. The field hold a number. Each entity's control field holds a different number. So each of the 20+ entries have it.

Doctrine offers several ways to to sort and get a subset of entries from a collection. These include the different sorts and filter functions. But none provide a means to order the result you get in a custom fashion. In this case I need to have the record with control=1616 be first in the list, followed by 1617 then 518. The reason for this is this: Each of the entities has another field called fact. For some of the entities, fact field comes empty. Therefore when iterating, I would like to get the first available 'fact' in the order provided. The order is important.

I could create a function that queries the collection for the three (though it can be a varied number of items), iterate them to turn the key for each entity to the value of its control field, then simply use native PHP functions to arrangement the entities in the order required. But that would be very inefficient and counter-intuitive as collections become larger. After all, if I missed the fact (a text field) from all three, I need to keep going with the others in any order to get it. Hence the three should appear in the list first, followed by the others.

So was wondering if anyone has a different take on this problem, or whether an issue ought to be opened with Doctrine to request for this feature (though I don't know of any kind of push for such a feature to warrant its implementation).

John Miller
  • 527
  • 4
  • 15

1 Answers1

0

The following code will resolve your need:

$controlArray = [1616, 1617, 518];
$collection = $this->createQueryBuilder('c')
           ->andWhere("c.control in (:control)")
           ->setParameter('control', $controlArray)
           ->orderBy('c.control', 'ASC')
           ->getQuery()->getResult();
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77