简体   繁体   中英

SQL doctrine query that has as many results as values ​passed in parameters

Assume that I give to a function an array :

$arrValues = ['19', '4', '4', '18', '19']

To a function :

$objRequeteDoctrine = $this->getEntityManager()->createQueryBuilder()
    ->select('o')
    ->from('xxxxxx', 'o')
    ->where('o.id IN (:values)')
    ->andwhere('o.actif = 1')
    ->setParameter(':values', $arrValues );

return $objRequeteDoctrine->getQuery()->getResult();

Here, it'll retrieve 3 objects(duplicates removed). But what if I want to retrieve 5 objects, with duplicates ? Is that possible ?

Thanks.

It might not be the answer to your question to achieve this with Doctrine but can be a solution to your problem. What about generating the full array afterwards?

$arrValues = ['19', '4', '4', '18', '19'];

$objRequeteDoctrine = $this->getEntityManager()->createQueryBuilder()
    ->select('o')
    ->from('xxxxxx', 'o')
    ->where('o.id IN (:values)')
    ->andwhere('o.actif = 1')
    ->setParameter(':values', $arrValues );

$result = $objRequeteDoctrine->getQuery()->getResult();

// Get the object ids in a separate array to find their position in the result

$idsOnly = [];
foreach($result as $entity) {
    $idsOnly[] = $entity->getId();
}

// Find the key of the object by id in the first result

$fullResult = [];
foreach ($arrValues as $id) {
    $keyFound = array_search($id, $idsOnly);
    if ($keyFound !== false) {
        $fullResult[] = $result[$keyFound];
    }
}

return $fullResult;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM