Claudio Ferraro
Claudio Ferraro

Reputation: 4721

Is there a way to specify the value of a foreign key without any reference to the entity object or repositories in Doctrine

I have 2 Entities. Part and Inventory

class Part
{
/**
 *  @ORM\Id
 *  @ORM\Column(type="string")
 */
private $partNumber;

/** @ORM\Column(name="part_name", type="string") */
private $partName;

/** @ORM\Column(type="string") */
private $warehouseStatus;
....

Inventory.php

class Inventory
{
/**
 *  @ORM\Id
 *  @ORM\Column(type="integer")
 *  @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * One Product has One Shipment.
 * @ORM\OneToOne(targetEntity="Part")
 * @ORM\JoinColumn(name="part_number", referencedColumnName="part_number")
 */
private $partNumber;

/** @ORM\Column(type="decimal") */
private $inStock;

I create the Part in this way

class one {
   private function method1 {
       $part = new Part();
       $part->partNumber = 'blabla';
       $part->warehouseStatus = 1;
       .....
}

class two {
    private function method1 {
        $inv = new Inventory();
        $inv->partNumber = 'blabla'; // it crashes here
        $inv->inStock = 1;
        .....
    }
}

In class two I'm trying to make a relation with the first object but partNumber crashes since he is expecting an Entity Object as Part and not a string. Is there an integrated doctrine method to create a reference to the part entity without having to instantiate repositories and so forth.

Upvotes: 0

Views: 297

Answers (1)

mxlhz
mxlhz

Reputation: 1138

You need to use the getReference function from the EntityManager for that:

    /**
     * Gets a reference to the entity identified by the given type and identifier
     * without actually loading it, if the entity is not yet loaded.
     *
     * @param string $entityName The name of the entity type.
     * @param mixed  $id         The entity identifier.
     *
     * @return object|null The entity reference.
     *
     * @throws ORMException
     */
    public function getReference($entityName, $id);

In your case:

$inv->partNumber = $entityManager->getReference(Part::class, $thePartIdYouReference);

Upvotes: 1

Related Questions