Doctrine2 关联映射与条件 [英] Doctrine2 association mapping with conditions

查看:23
本文介绍了Doctrine2 关联映射与条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于Doctrine2 关联映射与条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆