我有以下两个实体:
<?php
namespace Site\AnnonceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Site\UserBundle\Entity\User;
/**
* Site\AnnonceBundle\Entity\Sujet
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Site\AnnonceBundle\Entity\SujetRepository")
*/
class Sujet
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
//Some code...
/**
*
* @ORM\ManyToOne(targetEntity="Site\UserBundle\Entity\User")
*/
private $user;
//getter/setter....
用户实体(FOSUserBundle):
<?php
namespace Site\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table()
*
*/
class User extends BaseUser{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function getId() {
return $this->id;
}
}
当我创建一个“Sujet”时,我做了(在 SujetController.php 中):
$em = $this->getDoctrine()->getEntityManager();
$sujet->setResolu(false);
$em->persist($sujet);
$em->flush();
它的作品,但是在数据库中插入的“Sujet”指的是用户空......所以在第二个版本中我做了这个:
$em = $this->getDoctrine()->getEntityManager();
$sujet->setResolu(false);
$sujet->setUser(new User($this->get('session')->get('user_id'))) ;//the user is already in the DB
$em->persist($sujet);
$em->flush();
但我收到此错误:
A new entity was found through the relationship 'Site\AnnonceBundle\Entity\Sujet#user' that was not configured to cascade persist operations for entity: . Explicitly persist the new entity or configure cascading persist operations on the relationship. If you cannot find out which entity causes the problem implement 'Site\UserBundle\Entity\User#__toString()' to get a clue.
我不明白,我已经与另一个 ORM (JPA) 合作过,它以这种方式工作......如何告诉“Sujet”与数据库中已经存在的实体相关的内容?
(对不起,如果我的英语不好)
编辑:它对我有用:
$user = $this->get('security.context')->getToken()->getUser();
$sujet->setUser($user);
$em->persist($sujet);
$em->flush();