我想更改實體值,例如,如果它是例如NULL。 不幸的是,我的代碼會導致異常 - 雖然在數據庫中創建了'翻譯'記錄,並且id由getId方法正確返回,但似乎沒有設置id。如何在使用Symfony2保存之前設置或更改實體值
這是相當簡單的代碼,爲什麼它不起作用?
public function createAction(Request $request)
{
$entity = new Word();
$form = $this->createForm(new WordType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
//works fine - database record is created
if($entity->getIdTranslation() == NULL){
$translation = new Translation();
$em->persist($translation);
$em->flush();
$entity->setIdTranslation($translation->getId());
}
$em->persist($entity);
//throws exception - Integrity constraint violation: 1048 Column 'id_translation' cannot be null
$em->flush();
return $this->redirect($this->generateUrl('admin_word_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
編輯:加入我的模型和映射信息的一部分:
Revelant詞映射:
/**
* @var integer $id_language
*
* @ORM\Column(name="id_language", type="integer")
*/
private $id_language;
/**
*@ORM\ManyToOne(targetEntity="Language", inversedBy="words")
*@ORM\JoinColumn (name="id_language", referencedColumnName="id")
*/
protected $language;
/**
*
* @ORM\ManyToOne(targetEntity="Translation", inversedBy="words")
* @ORM\JoinColumn(name="id_translation", referencedColumnName="id")
*/
protected $translation;
和翻譯:
class Translation
{
public function __construct() {
$this->words = new ArrayCollection();
}
/**
* @ORM\PrePersist()
*/
public function prePersist() {
$this->created_date = new \DateTime();
}
/**
*
* @ORM\OneToMany(targetEntity="Word" ,mappedBy="translation")
*/
protected $words;
另請注意: 我使用數據庫建模軟件(工作臺)而不是Symfony控制檯工具創建了我的數據庫模型,現在我試圖設置實體以反映數據庫模型。 我不確定它的正確方法 - 也許我的模型太複雜,無法與教義正常工作?
您能顯示實體原則映射嗎? – l3l0
問題更新 – stawek