Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 get Doctrine in Entity

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.

like image 421
Roboto6_1on Avatar asked Jan 25 '26 16:01

Roboto6_1on


2 Answers

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; 
}
like image 107
panche14 Avatar answered Jan 27 '26 06:01

panche14


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.

like image 33
goto Avatar answered Jan 27 '26 06:01

goto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!