Haritz
Haritz

Reputation: 1752

Using distinct Doctrine2

I am developing an application in symfony2 and using doctrine2. I created a custom repository class that has one function:

<?php

namespace Anotatzailea\AnotatzaileaBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * InterpretatzeaRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class InterpretatzeaRepository extends EntityRepository
{

    public function getInterpDesberdinak($value)
    {
          $qb = $this->createQueryBuilder('c')
              ->select('DISTINCT c.attribute')
               ->where('c.fer = :Value')
               ->setParameter('Value', $value);
          $Emaitza = $qb->getQuery()->getResult();
          return $Emaitza;
    }       

}

What I want to get with this function is an array of all the "Interpretatzea" objects that have a distinct c.attribute and all have c.fer = value. Is the query correct? I would also want to know how to pass the value parameter to the repository function. Thanks

Upvotes: 0

Views: 4806

Answers (1)

Darragh Enright
Darragh Enright

Reputation: 14146

A cursory look at your repository method suggests it looks okay :) IIRC, I think the use of DISTINCT there is fine. If you do have problems you can always do a GROUP BY instead.

As for calling the repo method in a controller and passing a $value variable to it, that's pretty straightforward; for example:

// in your controller
$value = 'foo';

// get doctrine connection from DI, etc.
$em = $this->getDoctrine()
    ->getEntityManager();

// get the repository object for your 
// entity and call your repository method
$result = $em->getRepository('AnotatzaileaAnotatzaileaBundle:Interpretatzea')
    ->getInterpDesberdinak($value);

// ... do something with your $result here

Note you use a concatenated version of your namespace and bundle, followed by a colon and the entity; e.g: AcmeTestBundle:User

Hope this helps :)

Upvotes: 1

Related Questions