Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request with multiple id Symfony2 Doctrine

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.

like image 375
Ajouve Avatar asked Nov 06 '13 14:11

Ajouve


4 Answers

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'));
like image 124
Piotr Pasich Avatar answered Nov 08 '22 06:11

Piotr Pasich


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)');
like image 22
manix Avatar answered Nov 08 '22 06:11

manix


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.

like image 21
TheFrost Avatar answered Nov 08 '22 06:11

TheFrost


Simply use:

$em->getRepository('YourBundle:YourEntity')->findById(array(1, 2, 3, 4));

Arrays are supported as parameters.

like image 20
flu Avatar answered Nov 08 '22 04:11

flu