在 Symfony2 的实体 getter 方法中选择相关实体


Select related entities in entity getter method in Symfony2

如何在Symfony2中创建自定义查找器,我可以从对象上下文(如getter方法)而不是存储库上下文中调用。这是我在实体存储库类中的查询:

public function getUpVotes($trip_id)
{
    return count($this->getEntityManager()
        ->createQueryBuilder()
        ->select('t')
        ->from('VputiTripBundle:Trip', 't')
        ->join('t.ratings', 'r')
        ->where('r.trip = :tid')
        ->andWhere('r.up = :up')
        ->setParameters(['tid' => $trip_id, 'up' => 1])
        ->getQuery()
        ->getResult());
}

这样做的目的是,我将能够调用它 $model->getUpVotes(),而不是调用实体存储库并手动传递参数。

如果您设置了关联,则可以使用带有过滤器的 get。

public function getUpVotes()
{
    return $this->ratings->filter(
        function (RatingInterface $rating) {
            return 1 === $rating->getUp();
        }
    );
}