是否有可能与Doctrine 2.4中的条件进行关联映射?我有实体文章和评论.评论需要得到管理员的批准.评论的批准状态存储在"已批准的布尔字段"中.
现在我将@OneToMany关联映射到实体文章中的注释.它映射所有评论.但我想仅映射已批准的评论.
就像是
@ORM\OneToMany(targetEntity="Comment", where="approved=true", mappedBy="article")
Run Code Online (Sandbox Code Playgroud)
会非常有帮助的.不幸的是AFAIK没有映射条件的地方,所以我尝试用继承来解决我的问题 - 我创建了两个类Comment的子类.现在我有ApprovedComment和NotApprovedComment以及SINGLE_TABLE继承映射.
@ORM\InheritanceType("SINGLE_TABLE")
@ORM\DiscriminatorColumn(name="approved", type="integer")
@ORM\DiscriminatorMap({1 = "ApprovedComment", 0 = "NotApprovedComment"})
Run Code Online (Sandbox Code Playgroud)
问题是,由于"已批准"列是鉴别器,我不能再将其用作实体注释中的字段.
tim*_*dev 38
您可以使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是特别好的,因为Doctrine非常聪明,只有在尚未加载集合的情况下才能访问数据库.
| 归档时间: |
|
| 查看次数: |
11234 次 |
| 最近记录: |