1
votes

i'm pretty new to Symfony and Doctrine and i'm facing a problem trying to set Class Table Inheritance. I have a parent Entity, called "TeamActionTarget", and 2 children called "Player" and "Competition". The model of my parent entity is the following :

// src/Van/TeamsBundle/Entity/TeamActionTarget.php

namespace Van\TeamsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Van\TeamsBundle\Entity\TeamActionTarget
 *
 * @ORM\Entity
 * @ORM\Table(name="van_teams_actions_targets")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="type_id", type="integer")
 * @ORM\DiscriminatorMap( {"1" = "Competition", "2" = "Player"} )
 */
abstract class TeamActionTarget
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }
}

Doctrine2 generated me a parent table, with 2 fields, "id" and "type_id", and 2 children tables, with their own unique fields. What I want to do now is to retrieve all children BY TYPE, from an integer value posted from a form.

So in a controller, I coded this :

$em->getRepository('VanTeamsBundle:TeamActionTarget')->findByTypeId($targetType);

But Symfony2 returns me an error : Entity "Van\TeamsBundle\Entity\TeamActionTarget" has no field "typeId" Which is true. The entity model doesn't contain this field, only the parent class does. So I tried to add this field in the entity model, but I get a error when trying to update the entity, saying there is a conflict between this field and the discriminator.

My question is pretty easy, How can I retrieve my children BY TYPE, posted from a form ?

1
you have to set a @OnetoMany relation from parent to childNisam
where am I supposed to add this ? In the parent entity or in the children entities ?VaN
In parent entity, you can add $TypeId and corresponding getters and seters pls refer octrine manual docs.doctrine-project.org/en/2.0.x/reference/…Nisam

1 Answers

3
votes

When using single table inheritance, you have to use the repository of the child class directly:

$em->getRepository('VanTeamsBundle:Player')->findAll();

If you would like to retrieve the different child entities dependent on a form, you have to use the entity alias (e.g. VanTeamsBundle:Player) as the form field value and pass it to the getRepository() method. Another way of doing this is by performing a custom mapping between the form field value and the entity alias using data transformers.