Doctrine2 association mapping with conditions

后端 未结 1 1217
谎友^
谎友^ 2020-12-04 22:28

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 c

相关标签:
1条回答
  • 2020-12-04 23:06

    You can use the Criteria API to filter the collection:

    <?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);
        }
    
    }
    

    This is especially nice, because Doctrine is smart enough to only go to the database if the collection hasn't already been loaded.

    0 讨论(0)
提交回复
热议问题