Doctrine2 named queries

doctrine-orm, symfony

Solution

You can use

NamedQuery - DQL. Example

use Doctrine\ORM\Mapping\NamedQuery;
use Doctrine\ORM\Mapping\NamedQueries;

/**
* @Entity
* @Table(name="cms_users")
* @NamedQueries({
*     @NamedQuery(name="activated", query="SELECT u FROM __CLASS__ u WHERE u.status = 1")
* })
*/
class CmsUser
{}

And call it like

$this->getDoctrine()->getRepository('MyBundle:CmsUser')
    ->createNamedQuery('activated')
    ->getResult();

NamedNativeQuery - SQL. More information here: http://docs.doctrine-project.org/en/latest/reference/native-sql.html#named-native-query

Collecting a queries in your EntityRepository, like:

namespace Acme\StoreBundle\Repository;

use Doctrine\ORM\EntityRepository;

class ProductRepository extends EntityRepository
{
    public function findAllOrderedByName()
    {
        return $this->getEntityManager()
            ->createQuery('SELECT p FROM AcmeStoreBundle:Product p ORDER BY p.name ASC')
            ->getResult();
    }
}

More information here: http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes

Similar topic here: https://groups.google.com/forum/?fromgroups#!topic/doctrine-user/K-D5ta5tZ3Y[1-25]

Problem

I can't find any documentation about named queries in Doctrine2. Please help. Does Doctrine2 have a named queries feature?

Original source