Doctrine2 关联映射与条件

2022-01-03 00:00:00 php doctrine-orm

是否可以在 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.

类似的东西

@ORMOneToMany(targetEntity="Comment", where="approved=true", mappedBy="article")

会很有帮助.不幸的是,AFAIK 在映射中没有 where 条件这样的东西,所以我试图用继承来解决我的问题 - 我创建了类 Comment 的两个子类.现在我有 ApprovedComment 和 NotApprovedComment 和 SINGLE_TABLE 继承映射.

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.

 @ORMInheritanceType("SINGLE_TABLE")
 @ORMDiscriminatorColumn(name="approved", type="integer")
 @ORMDiscriminatorMap({1 = "ApprovedComment", 0 = "NotApprovedComment"})

问题是,由于已批准"列是鉴别符,我不能再将其用作实体评论中的字段.

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 DoctrineCommonCollectionsCriteria;

class Article
{

    /**
     * @ORMOneToMany(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 足够聪明,只有在集合尚未加载的情况下才转到数据库.

This is especially nice, because Doctrine is smart enough to only go to the database if the collection hasn't already been loaded.

相关文章