2015-09-25 90 views
0

有兩個實體 - AssetAttachment,雙向映射OneToOne。每個Asset可以0..1Asset

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.uuid

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另一種方式?

回答

0

在學說中,重點在於你的實體,而不是你的數據庫結構。所以如果你想獲得一個關聯的實體,你不會通過外部的ID,而是關聯的實體。如果你不想教條執行查詢要做到這一點,你可以得到這個實體的引用:

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

你可以閱讀有關學說內部的文檔中引用:

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