Search code examples
phpsymfonysymfony-3.4

FindBy() method "or" / "and"


How can I use an or in a findBy method.

Exemple : I have an entity with id_user_one and id_user_two and I want to search by a findby method all entities were id = 1 for id_user_one or id_user_two.

Question was posted here but no one find an response that works ... hope that is possible :)

P.S. : if you know how it works for and too I will be glad to know it :)


Solution

  • No it is not possible to do that only using findBy. You either have to write a repository function yourself:

    $repo->createQueryBuilder('e')
       ->andWhere('e.id_user_one = :user_id')
       ->orWhere('e.id_user_two = :user_id') // change to andWhere depending on your needs
       ->setParameter('user_id', 1)
       ->getQuery()->getResult();
    

    or fetch the entities with two calls and then merge the results:

    $collection1 = $repo->findBy(['id_user_one' => 1]);
    $collection2 = $repo->findBy(['id_user_two' => 1]);
    $collection3 = new ArrayCollection(
        array_merge($collection1->toArray(), $collection2->toArray())
    );
    

    For your ps: $result = $repo->findBy(['id_user_one' => 1, 'id_user_two' => 1]);