请求具有多个id Symfony2 Doctrine

时间:2022-08-31 06:45:09

I've got an array of IDs and I'd like to get an entity array from my IDs array.

我有一个ID数组,我想从我的ID数组中获取一个实体数组。

I can't use find.

我不能用find。

The sql request looks like:

sql请求如下所示:

SELECT * FROM mytable WHERE id = 12 OR id = 10 ...

with a loop on my id array.

我的id数组上有一个循环。

4 个解决方案

#1


27  

How about using the QueryBuilder class:

如何使用QueryBuilder类:

$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:

或者DQL:

$query = $em->createQuery('SELECT m FROM MyTable m WHERE m.id IN(12, 10)');

#2


89  

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

你也可以在get no tin数组中传递参数,但是用逗号粘贴的简单字符串

?ids=1,2,3,4,56

And after that get it from $request

然后从$ request获取它

$em->getRepository('YourRepo')->findById(explode(',', $request->get('ids'));

#3


19  

Simply use:

只需使用:

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

Arrays are supported as parameters.

支持数组作为参数。

#4


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.

效果是一样的。

#1


27  

How about using the QueryBuilder class:

如何使用QueryBuilder类:

$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:

或者DQL:

$query = $em->createQuery('SELECT m FROM MyTable m WHERE m.id IN(12, 10)');

#2


89  

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

你也可以在get no tin数组中传递参数,但是用逗号粘贴的简单字符串

?ids=1,2,3,4,56

And after that get it from $request

然后从$ request获取它

$em->getRepository('YourRepo')->findById(explode(',', $request->get('ids'));

#3


19  

Simply use:

只需使用:

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

Arrays are supported as parameters.

支持数组作为参数。

#4


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.

效果是一样的。