Question:
Good day.
There are two entities and there is a one-to-one relationship. These are users and user_info. I linked them like this:
/**
* Users
*
* @ORM\Table(name="users")
* @ORM\Entity
* @UniqueEntity("email")
*/
class User implements UserInterface
{
/**
* @var integer
* @ORM\Id
* @ORM\Column(nullable=false)
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
// ...
/**
* @ORM\OneToOne(targetEntity="AppBundle\Entity\UserInfo", mappedBy="user", cascade={"persist"})
*/
protected $information;
/**
* UserInfo
*
* @ORM\Table(name="user_info")
* @ORM\Entity
*/
class UserInfo
{
/**
* @var integer
* @ORM\Id
* @ORM\Column(nullable=false)
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="AppBundle\Entity\User", inversedBy="userInfo")
* @ORM\JoinColumn(name="id", referencedColumnName="id", nullable=false)
*/
protected $user;
I add data like this:
$user = $form->getData();
$user->setCreated(date('Y-m-d H:i:s'));
$user->getInformation()->setBalance(0);
$user->getInformation()->setRevShare(0);
$user->getInformation()->setMessengerType('skype');
$encoder = $this->container->get('security.password_encoder');
$encoded = $encoder->encodePassword($user, $user->getPassword());
$user->setPassword($encoded);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
The bottom line is that the id of the main entity (Users) is set, and the User_info id is set to null and PG refuses to execute such a request, they say, the id cannot be null, although, judging by the symfony profiler, the doctrine fulfills both requests:
SELECT NEXTVAL('users_id_seq');
SELECT NEXTVAL('user_info_id_seq');
What can be wrong?
Answer:
Apparently the problem is that you are trying to get the Information object from there, where it does not yet exist. Try to do as the documentation says – first create an object, then add it to the associated one:
...
$information = new UserInfo();
$information->setBalance(0)
->setRevShare(0)
->setMessengerType('skype');
$user->setInformation($information);
/**
вместо
$user->getInformation()->setBalance(0);
$user->getInformation()->setRevShare(0);
$user->getInformation()->setMessengerType('skype');
**/
...