Doctrine 2 Inheritance Mapping with Association

后端 未结 2 1525
面向向阳花
面向向阳花 2020-12-07 09:53

NOTE : if what I want is not possible, a \"not possible\" answer will be accepted

In the Doctrine 2 documentation about inheritance mapping, it says

2条回答
  •  -上瘾入骨i
    2020-12-07 10:29

    I'm tired, but this seems like much ado about nothing.

    You missed the important bit of that warning:

    If you use a STI/CTI entity as a many-to-one or one-to-one entity

    That's not the case in your example! If you had not omitted the doctrine annotations, you might have noticed.

    The association User::pets is OneToMany, not [One|Many]ToOne. One user has many pets.

    The inverse association is OneToOne, but it's targeting User, which has no inheritance.

    Robin's answer should have been a good hint -- you can log the sql queries and see what doctrine actually does to your database!


    The bad-for-performance scenario is something like:

    abstract class Pet { ... }
    
    class Cat extends Pet { ... } 
    
    class Dog extends Pet { ... }
    
    class Collar {
       /**
        * @Column(length="16")
        */
    
       protected $color;
       /**
        * ManyToOne(targetEntity="Pet")
        */
       protected $owner;
    }
    

    Now, if you wanted to iterate over all the blue collars, Doctrine runs into some trouble. It doesn't know what class $owner is going to be, so it can't use a Proxy. Instead, it's forced to eagerly load $owner to find out whether it's a Cat or a Dog.

    This isn't a problem for OneToMany or ManyToMany relationships, because in that case, lazy loading works fine. Instead of a proxy, you get a PersistentCollection. And a PersistentCollection is always just a PersistentCollection. It doesn't care about it's own contents until you actually ask for them. So lazy loading works fine.

提交回复
热议问题