Doctrine ORM 索引正确使用

Rob*_*zzi 1 orm doctrine relational-database symfony doctrine-orm

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

manager_id | business_id
1          | 1
1          | 2
1          | 3
Run Code Online (Sandbox Code Playgroud)

我在设置关系时没有问题,但是关于索引设置我不清楚

这是我的 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
Run Code Online (Sandbox Code Playgroud)

这是我的 Business.orm.yml

 Business:
    //...
    oneToMany:
        managers:
            targetEntity: User\ManagerBundle\Entity\Manager
            mappedBy: pharmacyBusiness
            indexBy: business_id # is this correct?
Run Code Online (Sandbox Code Playgroud)

这种关系以及约束的行为都如我所愿。但是,索引已成功创建。

我唯一关心的是该条款indexBy几乎适用于我输入的任何值。我应该使用什么值?如您所见,我给出了business_id值(索引列),但我不知道是否使用business_idbusiness__index (索引名称)。它以任何一种方式工作,但我不明白发生了什么:(

Jak*_*zak 5

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

第二件事是indexBy选择。我不确定你是否明白它的用途。此选项用于在您的实体中创建索引关联(在 PHP 级别)。它并没有真正影响数据库架构。

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

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

如果没有这个,您将需要遍历整个集合以找到具有特定 id 的经理。