Doctrine findBy array of UUIDs

117 Views Asked by At

I'm having a problem retrieving users by UUIDs using Doctrine in my Symfony application, and after a few hours of struggling without any real leads, I decided to ask the question here in case I missed something obvious.

Problem:
I have a Symfony application where users are identified by UUIDs.I'm trying to retrieve users from a list of UUIDs using Doctrine's findBy method, but I systematically get an empty array even though the UUIDs exist in the database.

Here my $id field:

trait UuidTrait
{
    #[ORM\Id]
    #[ORM\Column(type: UuidType::NAME, unique: true)]
    #[ORM\GeneratedValue(strategy: 'CUSTOM')]
    #[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
    private ?Uuid $id = null;

    public function getId(): ?Uuid
    {
        return $this->id;
    }
}

My Code to retrieve users:

$ids = ["018dd095-4c15-78b4-8f45-6c0bdc78368e","018dd226-5561-7b24-8677-64fa33a0267b"];
$users = $userRepository->findBy(["id" => $ids]); // -> empty array

I tried to convert my strings to UUIDs with:

$ids = array_map(fn (string $id) => Uuid::fromString($id), $ids);

But it still didn't work...

I checked my ids:

$users = $userRepository->findBy(["id" => $ids[0]]);

And $users contained 1 user so my ids were good.

The worst thing is that there are no errors thrown so I don't know where the problem is. I've seen several people use an array as a criteria parameter (here) so I assumed it was working.

Thanks in advance to anyone who can help me.

Geod

EDIT: Is saw this in the doctrine documentation and my code looks correct

1

There are 1 best solutions below

1
rahul On

It seems like Doctrine might not be able to handle a list of UUIDs all at once. So, I've come up with a solution to handle this situation. Hopefully, it works for you!

public function fetchByUuids(array $uuids){

    $qb = $this->createQueryBuilder('m');
    $expr = $qb->expr()->orX();
    foreach ($uuids as $key => $uuid) {
        $paramName = 'id_' . $key;
        $expr->add($qb->expr()->eq('m.id', ':' . $paramName));
        $qb->setParameter($paramName, $uuid, UuidType::NAME);
    }

    $qb->andWhere($expr);

    return $qb->getQuery()->getResult();
}

#[Route(path: '/home', name: 'home', methods: ['GET'])]
public function home(MoviesRepository $subscriberRepository)
{

    $ids = ['0188324d-103f-79dc-b313-fe8f85b9aaf4','0188324d-103f-79dc-b313-fe8f8adb328c'];
    dd($subscriberRepository->fetchByUuids($ids));


}

enter image description here