Roboto6_1on
Roboto6_1on

Reputation: 315

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.

Upvotes: 2

Views: 3381

Answers (4)

panche14
panche14

Reputation: 661

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

Upvotes: 3

rescobar
rescobar

Reputation: 1305

Into Post repository:

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

Upvotes: 2

goto
goto

Reputation: 8162

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.

Upvotes: 3

DonCallisto
DonCallisto

Reputation: 29932

//Topic.php

public function getPostsCount()
{
    return $this->getPosts()->count();
}

If you have configured annotations or yml properly, you're fine with this

Upvotes: 2

Related Questions