Symfony 2在实体中获取原则

Symfony 2在实体中获取原则,symfony,doctrine-orm,entity,Symfony,Doctrine Orm,Entity,我有两节课 class Topic { protected $id; //.... } 及 我想在Topic类中添加方法getPostCount()。在其他框架中,我曾经使用类似的方法: public function getPostCount() { $count = Post::find() ->where(['topic_id' => $t

我有两节课

    class Topic
    {
        protected $id;
        //....
    }

我想在Topic类中添加方法getPostCount()。在其他框架中,我曾经使用类似的方法:

 public function getPostCount()
    {        
            $count = Post::find()
                ->where(['topic_id' => $this->id])
                ->count();

        return $count;
    }
但在symfony2我不知道怎么做

//Topic.php

public function getPostsCount()
{
    return $this->getPosts()->count();
}
如果已正确配置注释或
yml
,则可以使用此方法创建注释。将存储库类名添加到实体的映射定义中,如下所示:

/**
*  @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
*/
class Post
{
    protected $topic_id;
    //...
}
在您的存储库类中:

public function getPostCount($id)
{        
     $query = $this->createQueryBuilder('p')
        ->select('count(p.topic_id)')
        ->where('p.topic_id = :id')
        ->setParameter('id', $id)
        ->getQuery()->getSingleScalarResult();
    return $query; 
}

除了@DonCallisto answer

//Topic.php
public function getPostsCount()
{
    return $this->getPosts()->count();
}
这是因为您已经定义了实体之间的关系

在实体内部进行查询不是一个好的做法,您应该使用
存储库

到后期存储库:

 public function getPostCount($id) {
    $qb = $this->getEntityManager()->createQueryBuilder();      
    $qb->select('count(p.topic_id)');
    $qb->from('AppBundle:Post', 't')
            ->where('p.topic_id = :id')
            ->setParameter('id', $id);
    $count = $qb->getQuery()->getSingleScalarResult();
    return $count;
}

你好,谢谢你的回答。如何使用您的解决方案在细枝视图中显示后计数?例如post.getPostCount(topic.id)?如果您只需要一个计数,请将变量从控制器传递给twig。另一方面,你们可以创建一个细枝过滤器,这是一个小例子,谢谢你们的回答。首先,你们并没有明确地做一个查询:这是一个为你们做这件事的原则,这是非常好的。第二:您可以在每次加载实体时对要水合的字段进行注释(但我相信在这种情况下您不会这样做,因为可能并非每次都需要PostScont)。这里唯一的“坏习惯”是性能问题。@DonCallisto查询部分是关于作者示例的。它的方法
getPostCount()
在实体内部(他使用
$this->id
)。我对你的回答没问题我只是解释了一些事情,对你的回答一点问题也没有!:)干杯
 public function getPostCount($id) {
    $qb = $this->getEntityManager()->createQueryBuilder();      
    $qb->select('count(p.topic_id)');
    $qb->from('AppBundle:Post', 't')
            ->where('p.topic_id = :id')
            ->setParameter('id', $id);
    $count = $qb->getQuery()->getSingleScalarResult();
    return $count;
}