In my zf2 project, I have doctrine 2 entities that reference the user entity as created by as the following:
/**
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(name="created_by", referencedColumnName="id")
**/
protected $createdBy;
and I want to set this reference in the PrePersist
, how can I do that?
I tried the following (I don't know if it is right):
/** @ORM\PrePersist */
public function prePersist() {
if ($this->createdBy === null) {
$session = new \Zend\Authentication\Storage\Session;
$userId = $session->read();
if ($userId !== null) {
$this->createdBy = $userId;
} else {
throw new \Exception("Invalid User");
}
}
}
but the main problem is that the $userId
is an integer, and createdBy
must hold the reference of the user not the user ID.
is there a better way to do that? if no, how can I get the reference instead of the user ID?