Search code examples
phpmongodbdoctrine-ormdoctrine-odm

Unable to break up a Doctrine ODM Query


SO I have the following Mongo ODM query that works just fine:

      $query = $dm->createQueryBuilder('MainClassifiedBundle:Listing')
         ->select('id', 'title', 'assets')
         ->field('somefield0')->equals($somefield)
         ->field('somefield')->equals($blah)
         ->field('somefield2')->range($minPrice, $maxPrice)
         ->field('somefield3')->near($latitude, $longitude)
         ->getQuery();

 $my_data = $query->execute();

However if I try to break it up like the following:

 $query = $dm->createQueryBuilder('MainClassifiedBundle:Listing')
     ->select('id', 'title', 'assets')
     ->field('somefield0')->equals($somefield)
     ->field('somefield')->equals($blah);

if ($propertyType != 'All') {
     $query->field('someothercrazyfield')->equals($somethingelse);

     $query->field('somefield2')->range($minPrice, $maxPrice)
     ->field('somefield3')->near($latitude, $longitude)
     ->getQuery();

 $my_data = $query->execute();

I get an error that method execute does not exist.

Why?


Solution

  • Because you are not storing the query when you call getQuery(). I've changed your example below.

    $query = $dm->createQueryBuilder('MainClassifiedBundle:Listing')
        ->select('id', 'title', 'assets')
        ->field('somefield0')->equals($somefield)
        ->field('somefield')->equals($blah);
    
    if ($propertyType != 'All') {
        $query->field('someothercrazyfield')->equals($somethingelse);
    
        $query->field('somefield2')->range($minPrice, $maxPrice)
           ->field('somefield3')->near($latitude, $longitude);
    }
    
    $my_data = $query->getQuery()->execute();