Symfony2如何在存储库中获取实体别名

时间:2014-02-05 09:24:44

标签: symfony

我想在我的实体存储库函数中编写一些DQL查询,但不是将实体别名编辑到DQL中,而是希望从存储库中获取实际的实体别名。 我的存储库:

/**
 * TrackingRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class TrackingRepository extends EntityRepository
{
    public function test()
    {
        $dql = 'SELECT * FROM MyBundle:Tracking';
        // i would like to call something like this:
        // $dql = 'SELECT * FROM ' . $this->getEntityAlias;
        $query = $this->getEntityManager()->createQuery($dql);
        ...
    }
}

这有可能吗?

3 个答案:

答案 0 :(得分:1)

您可以在存储库中获取带有$this->getClassName()的实体类:

class TrackingRepository extends EntityRepository
{
    public function test()
    {
        $dql = 'SELECT t FROM ' . $this->getClassName() . ' t';
        $query = $this->getEntityManager()->createQuery($dql);
        ...
    }
}

答案 1 :(得分:0)

您想要执行哪种查询?你真的需要DQL吗?还有其他方法可以执行复杂查询,请考虑:

存储库findBy($criteria)

public function test()
{
    $this-> findBy($criteria);
}

对于更复杂的查询,您还可以使用:

标准和匹配:

use Doctrine\Common\Collections\Criteria;

//

public function test()
{
    $criteria = Criteria::create()
        ->where(Criteria::expr()->eq('sth', 'val'))
        // more criteria here

    $result = $this->matching($criteria);
}

Doctrine's Query Builder

甚至是具有特定条件expressions的查询生成器:

public function test()
{
    $qb = $er->createQueryBuilder('p');
    $qb
        ->where($qb->expr()->andx(
            $qb->expr()->in('p', '?1'),
            $qb->expr()->isNotNull('p.someField')
        ))
        ->setParameter(1, $someValue);

    $result = $this->matching($criteria);
}

答案 2 :(得分:0)

class TrackingRepository extends EntityRepository
{
   public function test()
   {
    $dql = 'SELECT t.property1,t.property2,t.property3,t.property4 FROM MyBundle:Tracking t';
    // i would like to call something like this:
    // $dql = 'SELECT * FROM ' . $this->getEntityAlias;
    $query = $this->getEntityManager()->createQuery($dql);
    ...
   }
}