我有两个类
class Topic
{
protected $id;
//....
}
和
class Post
{
protected $topic_id;
//...
}
我想在 Topic 类中添加方法 getPostCount() 。在其他框架中我曾经使用类似的东西:
public function getPostCount()
{
$count = Post::find()
->where(['topic_id' => $this->id])
->count();
return $count;
}
但在 symfony2 中我不知道如何制作它。
最佳答案
您可以创建 repository class用这个方法。将存储库类名称添加到实体的映射定义中,如下所示:
/**
* @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;
}
关于Symfony 2 获得实体原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41961345/