Php 条令-添加指向2个目标实体的外键

Php 条令-添加指向2个目标实体的外键,php,database,symfony,doctrine-orm,foreign-keys,Php,Database,Symfony,Doctrine Orm,Foreign Keys,我有3个实体;博客,项目和评论。块和项目都有注释。因此,我希望在注释中使用外键ref_id,通过使用ref_type值指向Blog或Project。这里是我的实体 class Blog { ... protected $id; ... protected $title; ... } class Project { ... private $id; ... private $title; } class Comment { ... prote

我有3个实体;博客,项目和评论。块和项目都有注释。因此,我希望在注释中使用外键ref_id,通过使用ref_type值指向Blog或Project。这里是我的实体

class Blog
{
  ...
  protected $id;
  ...
  protected $title;
  ...
}

class Project
{
   ...
   private $id;
   ...
   private $title;
}

class Comment
{
  ...
  protected $id;

  /**
   * @ORM\Column(type="string")
   */
  protected $ref_type;

  /**
   * @ORM\ManyToOne(targetEntity="**Project,Blog**", inversedBy="comments")
   * @ORM\JoinColumn(name="ref_id", referencedColumnName="id")
  */
  protected $ref_id;

 }

我在理论上是新手,所以它可能很简单,但可以找到解决方案。在谷歌上,我遇到了映射的超类,但不确定它们与这个问题的关系。

是的,一个好的解决方案是将Blog和Project子类化

准备数据库 首先,你可以做出一个决定。假设这个超级类将被命名为Commentable

create table commentable( int id_commentable not null primary key auto_increment, title varchar(200) not null, c_type vachar(100) not null);
然后,每个可注释项都有其自定义字段:

/* blog table */
create table blog(id_commentable int not null primary key, description text);
/* project table */
create table project(id_commentable int not null primary key, location text);
请注意,上面的三个表具有相同的主键名称。这是强制性的

注释表与可注释表有关系

create table comments(id_comment int not null primary key auto_increment, comment text, commentable_id int not null);
创建超类和子类 根据表,现在是开始构建实体的时候了

可注释超类 博客 项目 评论 考虑到注释指向可注释实体而不是其子实体

/**
 * @Entity
 * @Table(name="comments")
 */

class Comment{

    /**
     * @ManyToOne(targetEntity="Commentable", inversedBy="comments")
     * @JoinColumn(name="comment_id", referencedColumnName="id_comment")
     **/
    protected $commentable;

    /**
     * @Column(type="string")
     */
    protected $comment;
用法 例如,如果需要项目注释,可以执行以下操作:

// knowing id 3 is a project
$project = em->find('models\Project', 3);
$comments = $project->getComments();
或者,如果您希望获得与类型无关的注释:

$commentable = em->find('models\Commentable', 3);
$comments = $commentable->getComments();
上述两个示例返回相同的注释列表

对于不同的注释类型,您需要一个注释主类和两个子类。可以使用将它们保存在一个表中。
/**
 * @Entity
 * @Table(name="comments")
 */

class Comment{

    /**
     * @ManyToOne(targetEntity="Commentable", inversedBy="comments")
     * @JoinColumn(name="comment_id", referencedColumnName="id_comment")
     **/
    protected $commentable;

    /**
     * @Column(type="string")
     */
    protected $comment;
// knowing id 3 is a project
$project = em->find('models\Project', 3);
$comments = $project->getComments();
$commentable = em->find('models\Commentable', 3);
$comments = $commentable->getComments();