1

I have an entity and i'm trying to create the following function inside its repository

function customGet(array $criteria)
{
     //WHAT I'm trying to do:
     //SELECT *
     //FROM mytable
     //LEFT JOIN anothoer table
     //WHERE criteria1 = value1 AND criteria2 = value2 ...etc

     $q = $this
        ->createQueryBuilder('u')
        ->select('u, g')
        ->leftJoin('u.theOtherTable', 'g');
        //Where here
        ->getQuery();
}

How can i do the where clause?

2 Answers 2

5
    $q = $this->createQueryBuilder('u')
        ->select('u, g')
        ->leftJoin('u.theOtherTable', 'g');

    foreach ($criteria as $field => $value) {
        $q->andWhere(sprintf('u.%s = :%s', $field, $field))
          ->setParameter($field, $value);
    }

    return $q->getQuery();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, It works perfectly, is it a good practice to use this to override Doctrine FindBy method ? since i'm having problem with fetch="EAGER" stackoverflow.com/questions/19421861/…
You should try to "filter" already on the Join if possible, but besides, this is in my opinion a good practice to write dedicated queries.
0

You can do it in this way if all entity association done correctly

function customGet(array $criteria)
    {
         $value1 = $criteria['0'];   //Your expected value
         $value2 = $criteria['1'];   //Your expected value

     $q = $this
        ->createQueryBuilder('u')
        ->select('u, g')
        ->leftJoin('u.theOtherTable', 'g');
        ->where('criteria1 = :value1 AND criteria2 = :value2')
        ->setParameters(array('value1'=>$value1,'value2'=>$value2))
        ->getQuery();

   return $q->getResult()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.