Doctrine2与条件的关联映射

克林基

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

现在,我有@OneToMany关联映射到实体Article中的注释。它映射所有评论。但我只想映射批准的评论。

就像是

@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"})

问题是,由于“已批准”列是区分符,因此我不能再将其用作实体Comment中的字段。

蒂姆德夫

您可以使用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非常聪明,仅在尚未加载集合时才去数据库。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章