我在使用Symfony2和Doctrine2作为ORM时,遇到了一个问题,即如何适当地跨bundle扩展实体。我希望能够使用UserBundle在没有BlogBundle的项目中,并且在具有User Bundle的项目中始终使用BlogBundle。
这可以通过将UserBundle\Entity\User对象从BlogBundle中扩展并向其中添加方法和属性来实现。但这会导致问题,因为两个实体都尝试映射并创建相同的表。尝试使用ResolveTargetEntityListener功能,但这与Mapped Superclas、STI和CTI都会强制使UserBundle依赖于BlogBundle。
@ORM\Table(name="app_user")
@ORM\Entity
class User implements UserInterface
{
...
}
博客捆绑实体帖子。
@ORM\Table(name="app_post")
@ORM\Entity
class Post
{
...
@ORM\Column(name="author_id", type="integer")
protected $author_id;
@ORM\ManyToOne(targetEntity="\App\BlogBundle\Entity\User", inversedBy="posts")
@ORM\JoinColumn(name="author_id", referencedColumnName="id")
protected $author;
}
BlogBundle\Entity\User
use App\UserBundle\Entity\User as BaseUser
@ORM\Entity
@ORM\table(name="app_user")
class User extends BaseUser
{
....
@ORM\OneToMany(targetEntity="App\BlogBundle\Entity\Post", mappedBy="author")
protected $posts;
public function __construct()
{
parent::_construct();
$this->posts = new \Doctrine\Common\Collections\ArrayCollection();
}
....
/* Getters & Setters, nothing that defines @ORM\Column, nothing persisted */
}
这个方案是可行的,但问题是我在项目中将两个实体映射到同一张表中。扩展对象没有从其父级获取@ORM\Table(name="app_user") ,因此必须在BlogBundle\Entity\User中定义该表。如果没有,在控制器中对此对象的任何引用都将无法访问数据库。由于扩展对象没有持久化任何内容,除了当我尝试从控制台更新数据库模式时会出错。
我可以使用单向关联,但这会限制我从控制器内部访问数据的方式。