How do I execute a query in MongoDB via Doctrine 2 ODM using PHP on Zend Framework2?

I have provided some sample code here. The query returns the entire db mapping instead of the data requested for, or an error with the abstract hydrator class.

Here's the code for the converter: -

    <?php


    namespace HelpostApi\Document;
    use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

    /** @ODM\Document(collection="posts") */

    class Post
    {

    /** @ODM\Id */
    private $id;

    /** @ODM\Field(type="string") */
    private $postTitle;
    /**
    * @param field_type $postTitle
    */
    public function setPostTitle($postTitle)
    {
    $this->postTitle = $postTitle;
    }
    /**
    * @param field_type $postTitle
    */
    public function getPostTitle()
    {
    return $this->postTitle;
    }
    }
    ?>

      

And here is the code for the controller including the request function: -

    <?php 
    namespace HelpostApi\Controller;

    use Zend\Mvc\Controller\AbstractRestfulController;
    use HelpostApi\Document\Post;

    class PostController extends AbstractRestfulController {
    public function getList() 
    {
    $dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
    print_r( $dm->createQueryBuilder('HelpostApi\Document\Post')
    ->hydrate(false)
    ->getQuery()
    ->getSingleResult()
    ->execute()
    );
    }

    ?>

      

+3


source to share


1 answer


If your request is simple, you can use one of the built-in ODM methods:

$this->dm->getRepository('HelpostApi\Document\Post')->find($id);

      

or



$criteria=array('key'=>'value');
$this->dm->getRepository('HelpostApi\Document\Post')->findOneBy($criteria);

      

Each of them will return either one HelpostApi \ Document \ Post object or NULL.

0


source







All Articles