Insert null into a Doctrine relationship

Asked

Viewed 93 times

1

I have a table of votes and a table of users, where for each vote entered the user can or can not be identified (relationship one-to-Many).

In case the user does not identify, how do I insert NULL in Foreign key user? I tried to create a new user object and perform the Insert but could not.

The error always returned is as follows:

A new Entity was found through the Relationship 'Portal Model Voto#usuario' that was not configured to Cascade persist Operations for Entity: Portal Model Usuario@00000199805b000000000453ebc2. To Solve this Issue: Either explicitly call Entitymanager#persist() on this Unknown Entity or configure Cascade persist this Association in the Mapping for example @Manytoone(..,Cascade={"persist"}). If you cannot find out which Entity causes the problem implement 'Portal Model Usuario#__toString()' to get a Clue.

2 answers

2

The problem in the specific case of your question, is that you are not persisting the user before persisting the vote. You should do something like this:

$entityManager->persist($user);
$vote->setUser($user);
$entityManager->persist($vote);
$entityManager->flush();

When allowing the user to be null, simply add the following annotation in the voting relationship (I believe that ManyToOne) for the user:

@ORM\JoinColumn(nullable=true)

1

I believe the problem can be solved with the configuration nullable=true in the Doctrine settings for your foreign key.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.