开发者

Problems with inheritance with Symfony2, Doctrine2

开发者 https://www.devze.com 2023-04-07 16:52 出处:网络
I edited some mistakes and details... Well, I have been trying to create a inheritance with Product as parent and Film and Book as childs. Checking online and the official documentation didn\'t solve

I edited some mistakes and details...

Well, I have been trying to create a inheritance with Product as parent and Film and Book as childs. Checking online and the official documentation didn't solved my problem because examples are poor and incomplete. (http://www.doctrine-project.org/docs/orm/2.0/en/reference/inheritance-mapping.html#class-table-inheritance).

I'm not sure if I did it right and now I just don't know how to generate, manipulate and persist inherited objects.

Parent class

<?php
name开发者_StackOverflow中文版space Paf\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table()
 * @ORM\Entity
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({ "film" = "FilmE2" , "book" = "BookE2" })
*/

class ProductEjemplo2 
{

/**
 * @var integer $id
 * @ORM\Id
 * @ORM\Column(name="id", type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;
//More fields, Name, Description ...
}

Child Class

<?php 
//Paf\MyBundle\Entity\FilmE2
namespace Paf\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table()
* @ORM\Entity
*/

class FilmE2 extends ProductEjemplo2
{
/**
  * @var integer $id
  * @ORM\Id
  * @ORM\Column(name="id", type="integer")
  */
 protected $id;
}

doctrine:schema:update --force generates 2 tables: ProductE...(id primary key, disc dunno how works, rest of fields) FilmE2(id primary key, rest of fields)

public function create2Action()  
{
$product1 = new ProductEjemplo2();
$product1->setName('New Film 1'); //and more fields
//here $product1 ID is null.(autogenerated but yet without value)
$em->persist($product1); //error, non-object....
$em->flush();

$film = new FilmE2();
$film->setName('New Film 1'); //and more fields
$film->setDirector('dir1');
$film->setId(1);
$em->persist($film); //error, non-object....
$em->flush();
//In both cases happens the same.

This doesn't work, it's quite obvious because says error "non-object" cant be persisted... but if I try with a new Filme2() happens the same... I realized that the ID of product is autogenerated when I use flush(). So isn't generated when I use persist...


You cannot have two primary keys in inherited class, simply because it lets you to persist base object class. You can find an example here it works fine. Except that its more complicated to use queries witch should filter specific instances but everything is possible

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号