Symfony 2 在实体中获得 Doctrine

Symfony 2 get Doctrine in Entity

我有两个classes

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

class Post
{
    protected $topic_id;
    //...
}

我想在主题 class 中添加方法 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,就可以了

您可以使用此方法创建 repository class。将存储库 class 名称添加到实体的映射定义中,如下所示:

/**
*  @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
*/
class Post
{
    protected $topic_id;
    //...
}

并且在您的存储库中 class:

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 回答

//Topic.php
public function getPostsCount()
{
    return $this->getPosts()->count();
}

这使用延迟加载原则:它可以完成,因为您已经定义了实体之间的关系。

在实体内部进行查询不是一个好的做法,您应该为此使用 Repository

进入 Post 存储库:

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