2016-02-25 35 views
0

我有一個理解的問題。Symfony獲得與語句映射實體(where子句)

我得到了2個映射實體

class news 
{ 
    public function __construct() 
    { 
     $this->newsgroups = new ArrayCollection(); 
    } 

    /** 
    * @ORM\ManyToMany(targetEntity="Unite\NewsBundle\Entity\newsgroup",  inversedBy="news") 
    * @ORM\JoinTable(name="news_to_newsgroup") 
    **/ 
    protected $newsgroups; 
.... 
} 

而且

class newsgroup 
{ 

    public function __construct() 
    { 
     parent::__construct(); 
     $this->news = new ArrayCollection(); 
    } 

    /** 
    * @ORM\ManyToMany(targetEntity="Unite\NewsBundle\Entity\news", mappedBy="newsgroups", cascade={"detach"}) 
    * @ORM\OrderBy({"undate" = "DESC"}) 
    **/ 
    protected $news; 
.... 
} 

我的問題: 我怎樣才能得到所有的新聞有活性和日期X和Y之間WHERE新聞組= 'X' 當我使用我的新聞組對象(函數getNews())

/** 
* Gets the groups granted to the user. 
* 
* @return Collection 
*/ 
public function getNews() 
{ 
    return $this->news ?: $this->news = new ArrayCollection(); 
} 

是否真的需要通過foreach來檢查每條新聞並檢查我的條件是否屬實?

非常感謝我的朋友們對你的幫助:)

回答

2

我建議你通過你的條件,以獲取新聞。查詢將會如此行事

$query = $repository->createQueryBuilder('n') 
      ->innerJoin('n.newsgoup', 'ng') 
      ->where('ng.id > :newsGroupId') 
      ->where('ng.undate BETWEEN :monday AND :sunday') 
      ->setParameter('newsGroupId', '1') 
      ->setParameter('monday', '2016-01-02') 
      ->setParameter('sunday', '2016-02-17') 
      ->getQuery(); 
    $news = $query->getResult(); 
+0

感謝您的回答,我正在考慮這種方式。我認爲還有另外一種方法可以從多元映射理論中獲得。所以它就像正常的msqli命令與教條一樣。非常感謝你:) – cRsakaWolf

+0

哈工作:D - innerJoin自動映射到新聞組,因爲許多映射。完善!謝謝 – cRsakaWolf

1

您可以使用Doctrine\Common\Collections\Criteria類來過濾集合。另外

public function getFilteredNews() 
{ 
    $criteria = Criteria::create() 
     ->where('isActive', true) 
     ->andWhere(Criteria::expr()->between(
      'createdAt', 
      '2016-02-20', 
      '2016-02-25' 
     )); 

    return $this->getNews()->matching($criteria); 
} 

,你可以使用filter方法從ArrayCollection或爲您的實體存儲庫,並獲取使用QueryBuilder數據(由安娜的建議):

你可以在你的實體創建一個額外的方法。

+0

好吧,所以我認爲這是我尋找的方式。我會嘗試你的解決方案。你認爲什麼是可持續發展和更強大的發展的更好方式? – cRsakaWolf

+1

我讀過,你的解決方案適用於教條2.5。 – cRsakaWolf

+0

是的,請在下次指定更多詳細信息,例如您正在使用的版本等。:)我會推薦QueryBuilder自定義查詢,但仍然依賴於用例。 – takeit

0

takeit我試過

/** 
* return active news 
*/ 
public function getActiveNews() 
{ 
    $criteria = Criteria::create() 
    ->where(Criteria::expr()->eq('unactive', true)) 
    ->andWhere(Criteria::expr()->gte(
      'unstartdate', 
      new \DateTime() 
      )) 
      ->andWhere(Criteria::expr()->lte(
        'unenddate', 
        new \DateTime() 
        )); 

      return $this->getNews()->matching($criteria); 
} 

現在得到錯誤「上PersistentCollection匹配標準僅適用於一對多協會的時刻。」