我有一个理解问题。
我有 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 之间的新闻 其中新闻组 = 'x'当我使用我的新闻组对象(函数getNews())时
/**
* Gets the groups granted to the user.
*
* @return Collection
*/
public function getNews()
{
return $this->news ?: $this->news = new ArrayCollection();
}
真的有必要用一个foreach浏览每个新闻并检查我的条件是否属实吗?
非常感谢我的朋友的帮助:)
我建议你根据你的条件来获取新闻。查询将像这样
$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();
可以使用
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);
}
或者,您可以使用ArrayCollection
中的过滤器方法,或者为您的实体创建一个存储库并使用 QueryBuilder 获取数据(如 Anna 建议的那样)。