Reputation: 2571
I want to have an alternative approach of the relationship referencing for each my Doctrine 2 entity: each entity relationship can be instantiated via id field or via reference field, and both fields mapped to the same database column.
Let me show:
/**
* @var integer
*
* @Column(name = "REF_ID", type = "integer", nullable = false)
*/
private $refId;
/**
* @var IBlock
*
* @ManyToOne(targetEntity = "Ref")
* @JoinColumn(name = "REF_ID", referencedColumnName = "ID")
*/
private $ref;
Whet I call persist for the such entity:
$entity = new Entity();
$entity->setName("Test entity");
$entity->setRefId(14);
I am getting the following error:
Column 'REF_ID' cannot be null
How can I implement workaround this? Is there any way to fix it?
Thanks!
Upvotes: 1
Views: 103
Reputation: 39390
You should set the $ref
attribute also, as example:
// Retrieve the $ref entity object as example with the repository
$ref = $refRepo->find(14)
//or
// $ref = $em->getRepository('Entity')->find($id);
// as described here in the doc
// http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#by-primary-key
$entity = new Entity();
$entity->setName("Test entity");
$entity->setRefId(14);
$entity->setRef($ref);
Hope this help
Upvotes: 1