Doctrine2关联映射与条件

时间:2014-05-04 08:38:47

标签: php doctrine-orm

是否可以与Doctrine 2.4中的条件进行关联映射?我有实体文章和评论。评论需要得到管理员的批准。评论的批准状态存储在布尔字段“approved。

现在我将@OneToMany关联映射到实体文章中的评论。它映射所有评论。但我想仅映射已批准的评论。

这样的东西
@ORM\OneToMany(targetEntity="Comment", where="approved=true", mappedBy="article")

会非常有帮助。不幸的是AFAIK没有映射条件的地方,所以我尝试用继承来解决我的问题 - 我创建了两个类Comment的子类。现在我有ApprovedComment和NotApprovedComment以及SINGLE_TABLE继承映射。

 @ORM\InheritanceType("SINGLE_TABLE")
 @ORM\DiscriminatorColumn(name="approved", type="integer")
 @ORM\DiscriminatorMap({1 = "ApprovedComment", 0 = "NotApprovedComment"})

问题是,由于“已批准”列是鉴别器,我不能再将其用作实体注释中的字段。

1 个答案:

答案 0 :(得分:34)

您可以使用Criteria API过滤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);
    }

}

这是特别好的,因为如果尚未加载集合,Doctrine足够聪明,只能访问数据库。

相关问题