0

There are two entities -- Asset and Attachment, mapped bidirectionally OneToOne. Each Asset can have 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;
    ...
}

Now I want to find() an Attachment by 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;
    }
    ...
}

But it doesn't and cannot work, since Doctrine expects an entity attribute name, rather than a table column name. Well, but here the entity doesn't have an attriute for the foreign key column.

How to use Doctrine\Common\Persistence#findBy(...) in this case? Or, if it's not possible: How to retrieve the Attachment by Asset.uuid in this concrete case another way?

automatix
  • 14,018
  • 26
  • 105
  • 230

1 Answers1

0

In Doctrine, the focus is on your entities, not on your database structure. So if you want to get an associated entity, you will not get it by a foreign ID, but the associated entity. If you don't want Doctrine to execute a query to do this, you can get a reference to this entity:

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

You can read about references in the documentation of doctrine internals:

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

StoryTeller
  • 1,673
  • 12
  • 30