Symfony2-Doctrine2 inheritance persist not working properly

那年仲夏 提交于 2019-12-07 21:05:23

问题


I have a project in Symfony 2.3, using Doctrine ORM 2.3.4, and I'm using class inheritance:

a parent class

/**
 * @ORM\Entity
 * @ORM\Table(name="parent")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"child"="Child"})
 */
class Parent
{
   /**
    * @ORM\Column(name="id", type="integer")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
   private $id;

   public function getId()
   {
      return $this->id;
   }

   // other fields & methods
}

and a child one

/**
 * @ORM\Entity
 * @ORM\Table(name="child")
 */
class Child extends Parent
{
   /**
    * @ORM\Column(name="id", type="integer")
    * @ORM\Id
    */
   private $id;

   public function getId()
   {
      return $this->id;
   }
}

The problem comes when I persist the child object, flush and then I try to retrieve the child id:

// ChildController::createAction

$em = $this->getDoctrine()->getManager();
$child = new Child();
// set child fields
$em->persist($child);
$em->flush();

$child->getId(); // <- not working

On the database the child row is saved correctly, and if I change the child method getId

public function getId()
{
   return parent::getId();
}

it works.

Can anyone please explain this to me?

Many thanks.


回答1:


The parent entity needs to give visibility of it's properties to it's children.

Change your $id property visibility to "protected".




回答2:


It's a little bit late, but maybe it helps others.

When you take a look at your table definition that Doctrine generated, you will see why it is this way. E.g. mine in postgres:

...
CONSTRAINT fk_5d9f75a1bf396750 FOREIGN KEY (id)
      REFERENCES parent (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
...

As you can see, Doctrine uses for your child table id the id of the parent. Like @John Cartwright said, make your $id in parent protected. In addition to this define the getter only in the parent and everything works just fine.



来源:https://stackoverflow.com/questions/19079322/symfony2-doctrine2-inheritance-persist-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!