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 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题