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;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程