是否可以使用 Doctrine 创建与通用表/类的关系?
下面是一些代码,以便于理解:
// class Log...
// TODO:
// It could be useful to have a reference to
// the element mentioned by the log, the issue is
// we don't know what kind of entity it is.
/**
* @ORM\ManyToOne(targetEntity="???")
*/
private $elementId
也许我可以不使用 targetEntity
而只使用 int,它是位于未知表中的元素的 id。
最佳答案
现在没有内置的可能性。
让我提出一个使用 Doctrine Lifecycle Events 的解决方案:
创建 3 个属性:
/* * @ORM\Column(name="element_class", type="string") */ private $elementClass /* * @ORM\Column(name="element_id", type="integer") */ private $elementId // Not mapped private $element public function setElement($element) { $this->element = $element; $this->elementClass = get_class($element); $this->elementId = $element->getId(); } public function getElement() { return $this->element; } // You need these for the PostLoad event listener : public function hydrateElementPostLoad($element) { $this->element = $element; } public function getElementClass() { return $this->elementClass; } public function getElementId() { return $this->elementId; }
然后创建一个能够水合元素属性的 PostLoadListener :
namespace AppBundle\EventListener; use Doctrine\ORM\Event\LifecycleEventArgs; use AppBundle\Entity\Log; class PostLoadListener { public function postLoad(LifecycleEventArgs $args) { $entity = $args->getEntity(); if($entity instanceOf Log){ $em = $args->getEntityManager(); $entity->hydrateElementPostLoad( $this->em->getRepository($entity->getElementClass())->findOneById($entity->getElementId()) ); } } }
并在您的 services.yml 中注册此事件:
services: places.listener: class: AppBundle\EventListener\PostLoadListener tags: - { name: doctrine.event_listener, event: postLoad }
这也是最著名的日志记录包的工作方式 ( The Gedmo DoctrineExtensions Logger )
要检索实体的所有日志,请为您的日志实体创建存储库方法:
getLogs($entity) { return $this->_em->findBy(array( 'element_id'=>$entity->getId(), 'element_class'=>get_class($entity) )); }
关于php - Doctrine 映射到未知实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38762286/