Doctrine2关联映射与条件 [英] Doctrine2 association mapping with conditions
问题描述
是否可以在Doctrine 2.4中使用关联映射与条件?我有实体文章和评论。评论需要由管理员批准。评论的批准状态存储在已批准的布尔字段中。
is it possible to have association mapping with conditions in Doctrine 2.4? I have entities Article and Comment. Comments needs to be approved by admin. Approval status of comment is stored in boolean field "approved.
现在我已经将@OneToMany关联映射到实体文章中的注释,它映射了所有的注释,但我想只能批准批准的评论。
Now I have @OneToMany association mapping to comments in entity Article. It maps all the comments. But I would like to map only approved comments.
像
@ORM\OneToMany(targetEntity="Comment", where="approved=true", mappedBy="article")
将是非常有益的,不幸的是,AFAIK没有像映射中的条件那样的东西,所以我试图解决我的继承问题 - 我创建了类注释的两个子类,现在我有ApprovedComment和NotApprovedComment和SINGLE_TABLE继承映射。 / p>
would be very helpful. Unfortunately AFAIK there is no such thing as where condition in mapping, so I tried to solve my problem with inheritance - I created two subclasses of class Comment. Now I have ApprovedComment and NotApprovedComment and SINGLE_TABLE inheritance mapping.
@ORM\InheritanceType("SINGLE_TABLE")
@ORM\DiscriminatorColumn(name="approved", type="integer")
@ORM\DiscriminatorMap({1 = "ApprovedComment", 0 = "NotApprovedComment"})
问题是,因为已批准列是歧视的r,我不能使用它作为实体评论中的字段。
Problem is, since "approved" column is discriminator, I cannot use it as field in entity Comment anymore.
推荐答案
您可以使用Criteria API过滤集合:
You can use the Criteria API to filter the collection:
<?php
use Doctrine\Common\Collections\Criteria;
class Article
{
/**
* @ORM\OneToMany(targetEntity="Comment", mappedBy="article")
*/
protected $comments;
public function getComments($showPending = false)
{
$criteria = Criteria::create();
if ($showPending !== true) {
$criteria->where(Criteria::expr()->eq('approved', true));
}
return $this->comments->matching($criteria);
}
}
这是特别好的,因为教义足够聪明,只有在集合尚未加载的情况下才能进入数据库。
This is especially nice, because Doctrine is smart enough to only go to the database if the collection hasn't already been loaded.
这篇关于Doctrine2关联映射与条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!