2013-08-01 60 views
0

考慮下列實體:學說ORM和繼承

class Entity { 
    protected $id; 
} 
class User extends Entity { 
    /** @var Entity */ 
    protected $target; 
} 
class Document extends Entity { 
    protected $title; 
} 
class Report extends Entity { 
    protected $level; 
} 

映射什麼,我需要創造這樣的學說可以正確映射User實體。 這裏的問題是,我希望能夠讓User::$target使用任何實體(因此Entity類型提示),並在代碼後面能夠作出相應的響應,這取決於它是Document還是Report

這也意味着,在代碼中,我需要能夠獲取任何Entity::$title如果它是一個DocumentEntity::$level如果它是一個Report

我可以通過教義來實現嗎?

回答

1

這應該很好。我沒有添加默認註釋,如「@ORM \ Entity」(http://docs.doctrine-project.org/en/latest/reference/annotations-reference.html。 我希望這是你正在尋找的,否則讓我知道。

/** 
* @ORM\InheritanceType("SINGLE_TABLE") 
*/ 
class Entity { 
    protected $id; 
} 

class User extends Entity { 
    /** 
    * @ORM\ManyToOne(targetEntity="Entity") 
    * @var Entity 
    */ 
    protected $target; 
} 

看一看:http://docs.doctrine-project.org/en/2.0.x/reference/inheritance-mapping.html 您應該使用過類表繼承由於性能問題,單繼承。

否則,Doctrine將連接實體表的子表,因爲Doctrine不知道「實體」具有哪種類型。例如:

SELECT t1.id, t2.title, t3.level FROM entity t1 LEFT JOIN document t2 ON t2.id = t1.id LEFT JOIN report t3 ON t3.id = t1.id 

更多的子表將導致更多的連接 - >緩慢。

這是如何檢查目標是文檔還是報告以及確定您必須訪問哪個字段。

// loads all users 
$users = $this->em->getRepository('User')->findAll(); 
foreach($users as $user){ 
    $target = $user->getTarget() 
    if($target instanceof Document){ 
     echo $target->getTitle(); 
    } 
    else if($target instanceof Report){ 
     echo $target->getLevel() 
    } 
}