如何使用findBy($ creteria)进行双向OneToOne映射?

时间:2015-09-25 15:21:19

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

有两个实体 - 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;
    ...
}

现在我要find() Attachment Asset.uuidclass AssetService ... { ... private function finAttachmentByAssetUuid($assetUuid) { $entityManager = $this->getEntityManager(); $attachmentRepository = $entityManager->getRepository('MyLib\Model\Entity\Attachment'); $attachment = $attachmentRepository->findBy([ 'attachment_linkassetuuid' => $assetUuid ]); return $attachment; } ... }

Doctrine\Common\Persistence#findBy(...)

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

在这种情况下如何使用Attachment或者,如果不可能:如何在此Asset.uuid中检索// Dont forget the "http://". A lot of browser add it themselves but the WebClient doesnt. string remoteUri = "download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,aapl&f=o&e=.csv"; // I recommend to take the habitude to write each one in one line. string fileName = "aapl.csv", myStringWebResource = null; // Use the "using" keyword to dispose WebClient WebClient myWebClient = new WebClient(); // Why are you doing this? Your url is working without. No need to concat here. myStringWebResource = remoteUri + fileName; // Download the Web resource and save it into the current filesystem folder. myWebClient.DownloadFile(myStringWebResource, fileName); 具体案例的另一种方式?

1 个答案:

答案 0 :(得分:0)

在Doctrine中,重点是您的实体,而不是您的数据库结构。因此,如果您想获得一个关联实体,您将无法通过外部ID获取它,而是获得相关实体。如果您不希望Doctrine执行查询来执行此操作,您可以获得对此实体的引用:

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

您可以阅读doctrine internals文档中的参考文献:

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