2014-02-05 82 views
0

我想在我的實體存儲庫函數中編寫一些DQL查詢,而不是將實體別名存入DQL中,我想從存儲庫中獲取實際的實體別名。 我的倉庫:Symfony2如何獲取存儲庫中的實體別名

/** 
* 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); 
     ... 
    } 
} 

是這個莫名其妙可能嗎?

回答

0

你可以得到$this->getClassName()實體類在你的倉庫:

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

好這產生: 「SELECT * FROM MyBundle \實體\跟蹤爲T」 而引起的異常,我需要: 「SELECT * FROM MyBundle :跟蹤AS t「 – gondo

+0

看我的代碼:用」t「代替你的」*「。 – ncrocfer

+0

它會解決什麼問題? – gondo

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); 
} 

學說的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); 
} 
+0

findBy是不夠的。我需要創建複雜的查詢,這就是爲什麼我使用DQL。反正這與我的問題沒有關係 – gondo

+0

@gondo我已經更新了我的答案。你真的需要DQL嗎?請考慮我的提示。 – NHG

+0

好吧,我的查詢看起來像這樣,如果你可以重寫它到QueryBuilder中,它會使它看起來不像DQL那麼複雜:'SELECT ta,tb,tc,td,te,tf FROM table t WHERE ta = 0 AND tb <> 2 AND UNIX_TIMESTAMP(COALESCE(tc,0)) gondo

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); 
    ... 
    } 
} 
+0

這是怎樣解決我的問題的?您仍在使用您的查詢中的編碼別名MyBundle:Tracking – gondo

相關問題