Symfony使用statement(where子句)获取映射实体

I got a understanding question.

I got 2 mapped Entities

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

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

And

class newsgroup
{

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

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

My question: how can i get all news which are active and between date x and y WHERE newsgroup = 'x' when i'm using my newsgroup object (function getNews())

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

Is it realy necessary to go through each news with a foreach and check if my conditions are true?

Thanks a lot my friends for your help :)

I suggest you to get news by your conditions. Query will be smth like this

$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();

You can use Doctrine\Common\Collections\Criteria class to filter the collection.

You may create an extra method in your entity:

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

Alternatively, you could use filter method from ArrayCollection or create a repository for your entity and fetch the data using QueryBuilder (as suggested by Anna).