dongzhang5006 2014-07-03 15:58
浏览 99
已采纳

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

I have two entities Post and Comment.
Structure:

Post: id title body

Comment: id post_id body active

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;

As a result when I want to get all comments for a post I use $post->getComments() and it works. How I can add extra Where clauses into this relationship if I want to get only posts with active = 1. I know that I can do it by DQL or queryBuilder but I want to know how I can do it by mapping

  • 写回答

1条回答 默认 最新

  • duanbianweng5353 2014-07-03 21:03
    关注

    I think the cleanest way to retrieve only active comments is to use Doctrine's Criteria object in the getComments method of your Post entity

    use Doctrine\Common\Collections\Criteria;
    

    and

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

    Edit

    If you want to prevent multiple queries each time you retrieve the active comments, you'll need to store them in a local variable. Instead of modifying getComments, you could add $active_comments and getActiveComments, which will populate $active_comments and only query the db if $active_comments is 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;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于php中URL传递GET全局变量的问题
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件