Access level problems when using Class Table Inheritance
I'm trying to implent the Class Table Inheritance Doctrine 2 offers in my Symfony 2 project. Let's say a have a Pizza class, Burito class and a MacAndCheese class which all inherit from a Food class.
The Food class has the following settings:
<?php
namespace Kitchen;
use DoctrineORMMapping as ORM;
/**
* @ORMEntity
* @ORMTable(name="food")
* @ORMInheritanceType("JOINED")
* @ORMDiscriminatorColumn(name="dish", type="string")
* @ORMDiscriminatorMap({"pizza" = "Pizza", "burito" = "Burito", "mac" => "MacAndCheese"})
*/
class Food {
/**
* @ORMId
* @ORMColumn(type="integer")
* @ORMGeneratedValue(strategy="AUTO")
*/
protected $id;
And the inherited classes have these settings ( Pizza for example):
<?php
namespace Kitchen;
use DoctrineORMMapping as ORM;
/**
* @ORMEntity
* @ORMTable(name="food_pizza")
*/
class Pizza extends Food {
When running doctrine:schema:update --force from the Symfony 2 app/console I get an error about the access level of $id in the children of Food ( Pizza for example), stating it must be protected or weaker. I haven't declared $id anywhere in the Pizza , since I reckoned it would be inherited from Food .
So I tried to declare $id, but that gives me an error, cause I can't redeclare $id. I figure I need some kind of reference to $id from Food in Pizza , but the Doctrine 2 documentation didn't really give me a clear answer on what this would look like.
Hopefully you understand what I mean and can help me.
Apparently I should have investigated the code generated by doctrine:generate:entities a bit more. When I started my IDE this morning and seeing the code again, I noticed that it had 'copied' all of the inherited fields (like $id in Food , in the example above) to the children ( Pizza , in the example above).
For some reason it decided to make these fields private. I manually changed the access level to protected in all of the classes and I tried to run doctrine:schema:update --force again: it worked!
So, as in many cases, the solution was a good night's rest! ;)
If someone comes up with a better solution and / or explanation for this problem, please do post it. I'd be more than happy to change the accepted answer.
Something to keep in mind:
Every Entity must have an identifier/primary key. You cannot generate entities in an inheritance hierachy currently (beta) As a workaround while generating methods for new entities, I moved away from project inheritated entities and after generating I moved them back.
source
May be you should define the @ORMDiscriminatorMap in a such way:
/**
*
..
* @ORMDiscriminatorMap({"food" = "Food", "pizza" = "Pizza", "burito" = "Burito", "mac" => "MacAndCheese"})
*/
If you compare your code with the example from Doctrine site, you will see that they added parent entity to the DiscriminatorMap.
链接地址: http://www.djcxy.com/p/55046.html上一篇: Django性能调优技巧?
下一篇: 使用类表继承时的访问级别问题