0

I'm very new using Doctrine, is the first project I work with it and I'm having an error while I try to insert a new user.

The thing is I've got a class User with a foreign key Country and when I try to insert a user Doctrine also try to insert the country, the country already exists so PDO launch an integrity constraint violation and Doctrine a Doctrine\DBAL\DBALException.

I know the annotation cascade={"persist"} makes the country entity to be written in the db, without it, doctrine launch another error:

A new entity was found through the relationship 'User#country' that was not configured to cascade persist operations for entity: Country@0000000078b1861f00007f935266d9fe. 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 'Country#__toString()' to get a clue. 

I've tried with all cascade options and only with persist and all the error above doesn't come up...

Is there something like cascade={"no-persist"} or something that tells doctrine the value of this attribute must be already inserted in table country???

Some code:

/** * User * * @Table(name="user") * @Entity */ class User { ... /** * @var Country * * @OneToOne(targetEntity="Country", cascade={"persist"}) * @JoinColumn(name="country", referencedColumnName="id") */ private $country ... } /** * Country * * @Table(name="country") * @Entity */ class Country { ... /** * @var integer * * @Column(name="id", type="integer") * @Id */ private $id; } 

Any clue will be highly appreciated. Thanks.

2
  • maybe table alias is not defined. Commented Nov 17, 2013 at 11:33
  • If table alias is this: @Table(name="country"), then it is defined... Commented Nov 17, 2013 at 11:38

1 Answer 1

1

Put the cascade=persist back in.

You need to check the database to see if the country exists. Your insert with an existing country fails because the country object needs to be managed by the entity manager.

$country = $countryRepository->find($countryId); if (!$country) { $country = new Country(); $entityManager->persist($country); } $user->setCountry($country); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I ended up changing country type to integer and removing all relations, your way is simpler and better, thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.