Doctrine ORM 索引正确使用

Doctrine ORM indexBy proper usage

在学说 (Symfony) 中,我在两个实体之间存在 1-n 关系:一个经理拥有 n 个企业。

manager_id | business_id
1          | 1
1          | 2
1          | 3

我在设置关系方面没有问题,但关于索引设置我有些不清楚

这是我的Manager.orm.yml

Manager:
    //...
    indexes:
       business__index:
          columns: [business_id]

    //...
    manyToOne:
        business:
            targetEntity: Business
            inversedBy: managers
            cascade: ['persist', 'remove']
            orphanRemoval: true
            joinColumn:
                name: business_id
                referencedColumnName: id
                nullable: false

这是我的 Business.orm.yml

 Business:
    //...
    oneToMany:
        managers:
            targetEntity: User\ManagerBundle\Entity\Manager
            mappedBy: pharmacyBusiness
            indexBy: business_id # is this correct?

关系有效,约束也如我所愿。然而,索引创建成功。

我唯一关心的是 indexBy 子句,它几乎适用于我输入的任何值。 我应该使用什么值?如您所见,我给出了 business_id 值(索引列),但我不知道是使用 business_id 还是 business__index(索引名称)。无论哪种方式都可以,但我不明白发生了什么:(

首先,我认为您不需要在此处定义 business__index,因为它是一个外键,因此 RDBMS 无论如何都会在此列上创建索引。

第二件事是 indexBy 选项。我不确定你是否明白它是做什么用的。此选项用于在您的 entity(在 PHP 级别)中创建一个 indexed association。它并不真正影响数据库架构。

简而言之,如果您希望能够轻松地从集合中获取项目(managers 在您的情况下),您可能希望 Doctrine 以某种方式映射您的经理,其中每个经理都有一些价值是数组中的一个键(实际上是ArrayIterator),所以你可以像$this->managers[$someId]一样得到它。

既然定义的字段被用作键,很明显你应该使用一个唯一的。通常它是主键(Manager::$id 在你的情况下)。

否则,您将需要遍历整个集合以找到具有特定 ID 的经理。