Roberto Rizzi
Roberto Rizzi

Reputation: 1543

Doctrine ORM indexBy proper usage

In doctrine (Symfony) I have a 1-n relationship between two entities: a manager owns n businesses.

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

I had no problem in setting the relationship but there is something which is not clear to me regarding the index settings

this is my 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

And this is my Business.orm.yml

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

The relationship works as well as the constraints behave as I wish. Yet, the index is successfully created.

My only concern is about the clause indexBy which works almost whatever value I put in. What value should I use? As you can see I gave the business_id value (indexed column) but I don't know whether to use business_id or business__index (the index name). It works either way but I don't understand what is goin on :(

Upvotes: 1

Views: 3710

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15656

First of all, I don't think you need business__index definition here since it's a foreign key so RDBMS will create an index on this column anyway.

Second thing is the indexBy option. I'm not sure if you understand what is it for. This option is used to create an indexed association in your entity (on PHP level). It doesn't really affect DB schema.

In short words, if you want to be able to easily get item from a collection (managers in your case), you may want Doctrine to map your managers in a way where some value of each manager is a key in array (ArrayIterator actually), so you can get it like $this->managers[$someId].

Since defined field is used as key, it's obvious that you should use a unique one. Usually it's primary key (Manager::$id in your case).

Without this you would need to iterate through whole collection to find a manager with a particular id.

Upvotes: 5

Related Questions