Jordan
Jordan

Reputation: 231

Doctrine 2 - Persist Entity with Joined Table's Foreign Key Opposed to Foreign Entity

I'm trying to persist a TradeEntity. A TradeEntity has a OneToOne relationship with a CurrencyEntity.

  /**
    * @ORM\OneToOne(targetEntity="Repositories\Currency\CurrencyEntity")
    * @ORM\JoinColumn(name="currency", referencedColumnName="id")
    *
    * @var CurrencyEntity
    */
    protected $currency;

I have recieved a CurrencyEntity from another object which I'm trying to insert in this new TradeEntity and persist it to the database but get an exception:

Type: Doctrine\ORM\ORMInvalidArgumentException
Message: Expected value of type "Repositories\Currency\CurrencyEntity" 
for association field "Repositories\Trade\TradeEntity#$currency", got "integer" instead.

Is there no other way of me persisting TradeEntity without fetching the CurrencyEntity from the database and setting it that way?

Upvotes: 4

Views: 449

Answers (1)

Alex Tartan
Alex Tartan

Reputation: 6826

In light of my recent discovery, i felt the need to update this answer.

Reading about Doctrine's advanced configuration, i came across Reference Proxies.

The method EntityManager#getReference($entityName, $identifier) lets you obtain a reference to an entity for which the identifier is known, without loading that entity from the database.

This is useful, for example, as a performance enhancement, when you want to establish an association to an entity for which you have the identifier. You could simply do this:

<?php
// $em instanceof EntityManager, $cart instanceof MyProject\Model\Cart
// $itemId comes from somewhere, probably a request parameter
$item = $em->getReference('MyProject\Model\Item', $itemId);
$cart->addItem($item);

Old answer:

What you can do is (it defeats the purpose of an ORM, but it is possible):

$conn = $entityManager->getConnection();
$conn->insert(
    'table_name', 
    array(
        'column_name' => 'column_value',
        // define all the columns here 
    )
);

See Doctrine's Data Retrieval And Manipulation

Upvotes: 4

Related Questions