在Doctrine2中检索关系时如何添加额外的WHERE子句

时间:2014-07-03 15:58:30

标签: php doctrine-orm

我有两个实体发布和评论 结构:

发表: ID 标题 体

注释: ID POST_ID 身体 活性

class Post
{
/**
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(name="title", type="string", length=255)
 */
private $title;

/**
 * @ORM\Column(name="body", type="text")
 */
private $body;

/**
 * @ORM\OneToMany(
 *     targetEntity="Comment",
 *     mappedBy="post"
 * )
 */
private $comments;

class Comment
{
/**
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(name="body", type="text")
 */
private $body;

/**
 * @ORM\ManyToOne(
 *      targetEntity="Post",
 *      inversedBy="comments"
 * )
 * @ORM\JoinColumn(
 *      name="post_id",
 *      referencedColumnName="id"
 * )
 */
private $post;

因此,当我想获得帖子的所有评论时,我使用$ post-> getComments()并且它有效。 如果我想只获得active = 1的帖子,如何在这段关系中添加额外的Where子句。 我知道我可以通过DQL或queryBuilder来实现它,但我想知道如何通过映射来实现它

1 个答案:

答案 0 :(得分:0)

我认为只检索有效评论的最简洁方法是在Criteria实体的getComments方法中使用Doctrine的Post对象

use Doctrine\Common\Collections\Criteria;

public function getComments()
{
    $criteria = Criteria::create();
    $criteria->where(Criteria::expr()->eq('active', 1));        
    return $this->comments->matching($criteria);
}

修改

如果要在每次检索活动注释时阻止多个查询,则需要将它们存储在本地变量中。您可以添加getComments$active_comments,而不是修改getActiveComments$active_comments$active_comments将填充false,仅在class Post { private $active_comments; public function getActiveComments() { if(!$this->active_comments) { $criteria = Criteria::create(); $criteria->where(Criteria::expr()->eq('active', 1)); $this->active_comments = $this->comments->matching($criteria); } return $this->active_comments; } 为{{1}}时才查询数据库。

{{1}}