Doctrine entities relationship

2020-05-09 01:42发布

问题:

I have an entity Template and another one Request. Essentially, a template represents an html form, and a request will represent a collection of values which the form was filled with and a reference to the template id.

class Request {
/**
 * @Id @Column(type="integer")
 * @GeneratedValue
 */
private $id;

/** 
 * @ManyToOne(targetEntity="Template", cascade={"persist"})
 * @JoinColumn(name="templateId", referencedColumnName="id", nullable=false)
 */
private $template;

...

What I am trying to achieve is that when Request is loaded from the DB then the object comes holding the relevant Template object with all its data. However, when requests are saved there is no need to save the template too... thus cascade={"persist"} should not be there.

1- Load all templates from db 2- User selects a template from a dropdown 3- Tmeplate shows on screen and the user fills it in 4- Request is saved

$request = new \entities\Request();
//template already exist in the db
$template = $this->templateRepository->fetchTemplate(1); 
$request->template = $template;
...
$this->entityManager->persist($request);
$this->entityManager->flush();

Now the problem is when I use casade persist it saves another Template in the templates table. If I do not use cascade persist it errors:

Fatal error: Uncaught exception 'Doctrine\ORM\ORMInvalidArgumentException' with message 'A new entity was found through the relationship 'entities\Request#template' that was not configured to cascade persist operations for entity: entities\Template@00000000343e07770000000073e3b0ec. 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 'entities\Template#__toString()' to get a clue.' in C:\Development\wamp\www\vendor\doctrine\orm\lib\Doctrine\ORM\ORMInvalidArgumentException.php on line 59

What is the correct Doctrine relationship setting to achieve the desired behaviour?