Search code examples
symfonydoctrine-orm

Doctrine EntityRepository for extended Entity


I am having problem with mapping custom entity repository to Entity which is extended from another entity.

Base entity:

/**
 * User entity
 *
 * @ORM\Table(name="user")
 * @ORM\Entity
 *
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="user_type", type="string")
 * @ORM\DiscriminatorMap({"user" = "User", "client" = "Client"})
 */
class User
{
}

Extended entity:

/**
 * Client entity
 *
 * @ORM\Entity(repositoryClass="Acme\AppBundle\Entity\ClientRepository")
 */
class Client extends User
{
}

Repository:

namespace Acme\AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * ClientRepository
 */
class ClientRepository extends EntityRepository
{
    /*
     * this method returns resultset
     * its empty just for simplification
     */
    public function getClientsWithActiveCampaign(\DateTimeInterface $date = null) {}
}

Calling the repository:

$clients = $this->getDoctrine()->getRepository('AcmeAppBundle:Client')->getClientsWithActiveCampaign();

But when I am calling custom method on ClientRepository I get:

Undefined method 'getClientsWithActiveCampaign'. The method name must start with either findBy or findOneBy!

So it seems that Doctrine doesn't know about my custom repository.


Solution

  • Thinking about this, the entity manager is missing and that is why it cannot find the repository. In your controller/service, use:

    $em = $this->getDoctrine()->getManager();
    $clients = $em->getRepository('AcmeAppBundle:Client')->getClientsWithActiveCampaign(); 
    

    The $clients variable should be populated now, or at least you will get a different error. The getClientsWithActiveCampaign function should run.