I have two classes
class Topic
{
protected $id;
//....
}
and
class Post
{
protected $topic_id;
//...
}
and I would like add method getPostCount() in Topic class. In other frameworks I used to use something like that:
public function getPostCount()
{
$count = Post::find()
->where(['topic_id' => $this->id])
->count();
return $count;
}
but in symfony2 I don't know how to make it.
You can create a repository class with this method. Add the repository class name to your entity's mapping definition, like this:
/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
*/
class Post
{
protected $topic_id;
//...
}
And in your repository 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;
}
In addition to @DonCallisto answer
//Topic.php
public function getPostsCount()
{
return $this->getPosts()->count();
}
This use doctrine lazyloading: it could be done because you already defined the relation between the entity.
It would not be a good practice to do a query inside the entity, you should use a Repository for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With