Caner
Caner

Reputation: 186

Create new element with doctrine entity manager?

I use doctrine entity manager in my script, select and update works always, so entity manager is initialized correctly:

$article = $entityManager->find('Models\Article', 5);
echo $article->getTitle();
or:
$article->setTitle('Updated!');

but when I try to create/save new element then the page breaks, the code is:

$item = new Article();
$item->setAuthorId(1);
$item->setTitle('Created item!');
$entityManager->persist($item);
$entityManager->flush();

It's created like on official documentation page

What I do wrong here?

Upvotes: 1

Views: 1357

Answers (1)

Matteo
Matteo

Reputation: 39470

Seems you can't specify the relation of the object with the Author entity:

$item->setAuthorId(1);

Probably your entity Article Have a relation with the entity Author. In this case you should have a proper setter method (simple setAuthor(Author $author) ) that assign the reference of an Author object. In this case you could use the following:

$item->setAuthor($entityManager->find('Models\Author', 1););

Or Better

$item->setAuthor($entityManager->getReference('Models\Author', 1););

You could also use a short way of reference the class object with the class keyword, as example:

$item->setAuthor($entityManager->getReference(Author::class, 1););

Hope this help

Upvotes: 2

Related Questions