I've got an array of IDs and I'd like to get an entity array from my IDs array.
I can't use find.
The sql request looks like:
SELECT * FROM mytable WHERE id = 12 OR id = 10 ...
with a loop on my id array.
You can also get it directly from repository:
$em->getRepository('YourRepo')->findById(array(1,2,3,4,5));
Also you can pass parameters in get no tin array, but in simple string glued by commas
?ids=1,2,3,4,56
And after that get it from $request
$em->getRepository('YourRepo')->findById(explode(',', $request->get('ids'));
How about using the QueryBuilder class:
$qb = $em->createQueryBuilder();
$qb->select('m');
$qb->from('MyEntity', 'm');
$qb->where($qb->expr()->in('m.id', array(12, 10)));
//ArrayCollection
$result = $qb->getQuery()->getResult();
Or DQL:
$query = $em->createQuery('SELECT m FROM MyTable m WHERE m.id IN(12, 10)');
In case you don't want to use magic methods, instead of using this working piece of code:
$em->getRepository('AppBundle:FooEntity')->findById([1, 2, 3]);
...you can use this:
$em->getRepository('AppBundle:FooEntity')->findBy(['id' => [1, 2, 3]]);
Effect is the same.
Simply use:
$em->getRepository('YourBundle:YourEntity')->findById(array(1, 2, 3, 4));
Arrays are supported as parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With