0

I am having problem in getting data from doctrine object. When I use findOne(id) and try to access any variable like $result->getVariable() it works fine. But as soon as I use doctrine query builder and add some conditions, it says

Attempted to call method "getVariable" on class "Doctrine\ORM\QueryBuilder....

My Code is

foreach ($Ids as $Id) {
            $result = $em->createQueryBuilder()->select("s")
                ->from("Entity", "s")
                ->where('s.id = :s_id')
                ->setParameters(array('s_id'=>$Id));
     if($category)
     {

        $result->innerJoin('s.cat','c');
        $result->where("c.primaryClassification =   :category");
        result->setParameter('category',$category);
    }

}

The Code which is working is

foreach ($Ids as $Id) {
$em->getRepository("Entity")->findOneById($Id);
}

I think it is the difference in data returned because of different types of methods used.

Thanks in advance!

1 Answer 1

1

That's because the QueryBuilder is only for that, to build querys (BA-DUM-TSS). What you need is to execute the query after you build it and set the parameter correctly for a =:

foreach ($Ids as $Id) {
    $query[] = $em->createQueryBuilder()->select("s")
        ->from("Entity", "s")
        ->where('s.id = :s_id')
        ->setParameter('s_id', $Id))
        ->getQuery()
        ->getResult();
}

also if you are looking for an array of data, is BEST if you use the IN statement without the foreach and pass the array directly to the setParameter:

$result = $em->createQueryBuilder()->select("s")
    ->from("Entity", "s")
    ->where('s.id IN (:s_id)')
    ->setParameter('s_id', $Ids)
    ->getQuery
    ->getResult();

If you need more info on the query builder check the docs.

Sign up to request clarification or add additional context in comments.

5 Comments

I would use setParameter (as setParameters need an array) and I would not use array_values as passing direclty the array is fine.
Second approach is still the best, you should also highlight that practice ;)
Thanks, now the answer is better worded.
Another alternative is like $queryBuilder = $em->getQuerBuilder(); $result = $queryBuilder...... ->where($queryBuilder->expr()->in('s.id', ':ids'))->setParameter('ids', $ids) rather than building the expression directly.
Ok. Your query is working thanks for that. Now I want to add an if condition in my query. I have updated my question for that. Sorry i did not posted initially in my question.

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.