dongshetao1814 2013-08-01 11:39
浏览 46
已采纳

主义ORM和继承

Given the following entities:

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

What mapping do I need to create so doctrine can map the User entity correctly. The problem here is, I want to be able to have User::$target use any Entity (hence the Entity type hint) and later in the code be able to respond accordingly, depending if it's a Document or a Report.

This also means, that in the code, I need to be able to fetch either Entity::$title if it's a Document or Entity::$level if it's a Report.

Can I achieve this with doctrine?

  • 写回答

1条回答 默认 最新

  • dqy92287 2013-08-01 13:04
    关注

    This should work fine. I did not add default annotations like "@ORM\Entity" (http://docs.doctrine-project.org/en/latest/reference/annotations-reference.html). I hope this is what you are looking for, otherwise let me know.

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

    Have a look at: http://docs.doctrine-project.org/en/2.0.x/reference/inheritance-mapping.html You should use Single Inheritance over Class Table Inheritance due performance issues.

    Otherwise Doctrine will make joins over child tables of the entity table because Doctrine doesn't know which type the "Entity" has. Something like:

     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 
    

    More child tables will result in more joins -> slow.

    This is how you check if target is a Document or a Report and to determine which field you have to access.

    // 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()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染