设计实体模型以管理多个双向关系


Design entity model to manage multiple bidirectionnal relations

我正在尝试从我的模型中找到设计实体之间关系的最佳方法。我会试着解释清楚的。

想象一下以下教义2实体:

class ImageHistory
{
    /**
     * @var Image
     */
    protected $current;
    /**
     * @var 'Doctrine'Common'Collections'Collection
     */
    protected $old;
}
class Dog
{
    protected $name;
    /**
     * @var ImageHistory
     */
    protected $imageHistory;
}
class Cat
{
    protected $name;
    /**
     * @var ImageHistory
     */
    protected $imageHistory;
}

我想建立两种一对多的双向教义关系,其中CatDog是关系的拥有方。CatDog类都具有以下实体配置:

manyToOne:
    imageHistory:
        targetEntity: ImageHistory
        joinColumn:
            name: image_history_id
            referencedColumnName: id

如何表示 te 关系的另一面?

oneToMany:
    owner:
        targetEntity: <What can I write here?>
        mappedBy: imageHistory

我设想了一个解决方案,其中CatDog继承一个Animal实体类,因此我可以将 ManyToOne 关系移动到 Animal 类中,并将Animal作为 OneToMany 关系的目标实体。但是如果我有一个新的SoundHistory实体并且:CatDog和新的CarBoat类必须与它有关系,问题就会再次出现。

A 不能只是将SoundHistory作为 oneToMany 关系添加到 Animal 类,因为CarBoat 不会从中继承。所以我仍然无法在ImageHistory实体中填充我的 OneToMany 关系的targetEntity

在这种情况下,设计实体模型的最佳方法是什么?

多对一关系是单向的,因此您不能代表另一方。

此外,如果您真的想将狗和猫存储在同一个表中,您应该考虑创建一个超级实体。

你需要的最好的方法是使用一个单独的连接表来表示CatDogImageHistory之间的关系,SoundHistory。为此,您可以将一对多单向映射与连接表一起使用。在这里找到的教义文档,感谢NaeiKinDus:https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/association-mapping.html#one-to-many-unidirectional-with-join-table

关键是 - 图像和声音历史记录是独立存储的,连接表cat_image_history存储哪个Cat拥有哪个ImageHistory。所以教义会得到你的猫id,检查cat_image_history并通过image_history_id获得正确的ImageHistory。同样,您可以只为狗或猫和狗添加SoundHistory

映射可能如下所示:

Cat:
  type: entity
  manyToMany:
    imageHistory:
      targetEntity: ImageHistory
      joinTable:
        name: cat_image_history
        joinColumns:
          cat_id:
            referencedColumnName: id
        inverseJoinColumns:
          image_history_id:
            referencedColumnName: id
            unique: true