我有关于双向OneToMany< - >的问题.我的实体Device和Event之间的ManyToOne关系.这是映射的外观:
// Device entity
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Event", mappedBy="device")
*/
protected $events;
// Event entity
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Device", inversedBy="events")
*/
protected $device;
问题出现是因为Device是单表继承实体
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="device_class_type", type="string")
每次我获取并迭代一些Event实体时,总是急切地获取$device.发生这种情况是因为它是relative documentation中报告的STI实体
There is a general performance consideration with Single Table
Inheritance: If the target-entity of a many-to-one or one-to-one
association is an STI entity, it is preferable for performance reasons
that it be a leaf entity in the inheritance hierarchy, (ie. have no
subclasses). Otherwise Doctrine CANNOT create proxy instances of this
entity and will ALWAYS load the entity eagerly.
现在有另一个名为Gateway的实体与Device和Event有关系:
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Device", mappedBy="gateway")
*/
protected $devices;
/**
* @ORM\OneToMany(targetEntity="targetEntity="AppBundle\Entity\Event", mappedBy="gateway")
*/
protected $events;
public function getEvents(): Collection
{
return $this->events;
}
当然,每当我遍历$gateway-> getEvents()时,所有相关事件设备都会被急切地获取.即使我没有获得任何$device信息,也会发生这种情况 – 一个空的foreach就足以让Doctrine为每个对象执行1个查询来获取相关的$device
foreach ($gateway->getEvents() as $event) {}
现在我知道我可以使用QueryBuilder设置一个不同的水合模式,避免$device fetching
return $this->getEntityManager()->createQueryBuilder()
->select('e')
->from('AppBundle:Event', 'e')
->where('e.gateway = :gateway')
->setParameter('gateway', $gateway)
->getQuery()->getResult(Query::HYDRATE_SIMPLEOBJECT);
但我想直接在Gateway实体中做到这一点.
那么可以直接在Gateway实体类中水合Gateway->事件吗?