[英]Doctrine2 association mapping with conditions
是否可以在 Doctrine 2.4 中对条件进行关联映射? 我有实体文章和评论。 评论需要管理员批准。 评论的批准状态存储在布尔字段“已批准”中。
现在我有 @OneToMany 关联映射到实体文章中的评论。 它映射了所有的评论。 但我只想映射已批准的评论。
就像是
@ORM\OneToMany(targetEntity="Comment", where="approved=true", mappedBy="article")
会很有帮助。 不幸的是,AFAIK 在映射中没有 where 条件这样的东西,所以我试图用继承来解决我的问题 - 我创建了类 Comment 的两个子类。 现在我有 ApprovedComment 和 NotApprovedComment 和 SINGLE_TABLE 继承映射。
@ORM\InheritanceType("SINGLE_TABLE")
@ORM\DiscriminatorColumn(name="approved", type="integer")
@ORM\DiscriminatorMap({1 = "ApprovedComment", 0 = "NotApprovedComment"})
问题是,由于“已批准”列是鉴别器,我不能再将其用作实体评论中的字段。
您可以使用 Criteria API 来过滤集合:
<?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);
}
}
这特别好,因为 Doctrine 足够聪明,只有在集合尚未加载的情况下才转到数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.