【问题标题】:How to use findBy($creteria) for a bidirectional OneToOne mapping?如何使用 findBy($creteria) 进行双向 OneToOne 映射?
【发布时间】:2015-09-25 15:21:19
【问题描述】:

有两个实体——AssetAttachment,双向映射OneToOne。每个Asset 可以有 0..1 Asset:

Asset

class Asset
{
    /**
     * @var string @ORM\Column(name="asset_uuid", type="string", length=36, nullable=false)
     *      @ORM\Id
     */
    private $uuid;
    /**
     * @var \MyLib\Model\Entity\Attachment
     * @ORM\OneToOne(targetEntity="MyLib\Model\Entity\Attachment", mappedBy="asset", cascade={"remove", "persist"}, orphanRemoval=true)
     **/
    private $attachment;
    ...
}

Attachment

class Attachment
{
    /**
     * @var string @ORM\Column(name="attachment_uuid", type="string", length=36, nullable=false)
     *      @ORM\Id
     */
    private $uuid;
    /**
     * @var \MyLib\Model\Entity\Asset
     * @ORM\OneToOne(targetEntity="\MyLib\Model\Entity\Asset", inversedBy="attachment", cascade={"persist"})
     * @ORM\JoinColumn(name="attachment_linkassetuuid", referencedColumnName="asset_uuid")
     */
    private $asset;
    ...
}

现在我想通过Asset.uuidfind()Attachment

class AssetService ...
{
    ...
    private function finAttachmentByAssetUuid($assetUuid)
    {
        $entityManager = $this->getEntityManager();
        $attachmentRepository = $entityManager->getRepository('MyLib\Model\Entity\Attachment');

        $attachment = $attachmentRepository->findBy([
            'attachment_linkassetuuid' => $assetUuid
        ]);

        return $attachment;
    }
    ...
}

但它不能也不能工作,因为 Doctrine 需要一个实体属性名称,而不是表列名称。好吧,但是这里的实体没有外键列的属性。

在这种情况下如何使用Doctrine\Common\Persistence#findBy(...) 或者,如果不可能:在这种具体情况下,如何以另一种方式通过Asset.uuid 检索Attachment

【问题讨论】:

    标签: orm doctrine-orm foreign-keys one-to-one bidirectional


    【解决方案1】:

    在 Doctrine 中,重点是您的实体,而不是您的数据库结构。所以如果要获取关联实体,就不会通过外来ID获取,而是关联实体。如果您不希望 Doctrine 执行查询来执行此操作,则可以获取对此实体的引用:

    /** @var EntityManager $em */
    $asset = $em->getReference('MyLib\Model\Entity\Asset', $assetId);
    $attachement = $asset->getAttachment();
    

    您可以阅读教义内部文档中的参考资料:

    http://doctrine-orm.readthedocs.org/en/latest/reference/unitofwork.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-02
      • 2014-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 2014-05-17
      • 1970-01-01
      相关资源
      最近更新 更多