我在尝试将实体和关联实体持久化到数据库时遇到以下异常。不知道我在这里做错了什么:
例外:
The given entity of type 'AppBundle\Entity\User'
(AppBundle\Entity\User@0000000065c3019f00000000123d7c75) has no
identity/no id values set. It cannot be added to the identity map.
实体:
/**
* @ORM\Entity
*/
class User
{
/**
* @ORM\Column(type="string")
*/
private $name;
/**
* @ORM\OneToOne(targetEntity="Address", inversedBy="user")
* @ORM\JoinColumn(name="address_id", referencedColumnName="id")
* @ORM\Id
*/
protected $address;
}
/**
* @ORM\Entity
*/
class Address
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
*/
private $id
/**
* @ORM\OneToOne(targetEntity="User", mappedBy="address", cascade={"all"}, fetch="LAZY")
*/
private $user;
}
实体创建:
$user = new User();
$address = new Address();
$address->setUser($user->setAddress($address));
$this->getDoctrine()->getManager()->persist($user);
$this->getDoctrine()->getManager()->persist($address);
$this->getDoctrine()->getManager()->flush();
答案 0 :(得分:0)
你必须为教义实体
指定一个ID 像这样:class User
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string")
*/
private $name;
/**
* @ORM\OneToOne(targetEntity="Address", inversedBy="user")
* @ORM\JoinColumn(name="address_id", referencedColumnName="id")
* @ORM\Id
*/
protected $address;
}
答案 1 :(得分:0)
请参阅:Doctrine OneToOne identity through foreign entity exception on flush,这有助于解决此问题。
实际对象地址需要先由EntityManager保存。仅仅将该类作为对另一个类的引用并不会使entityManager意识到两个类都存在的事实。考虑到这一点,以下代码允许我将这些对象持久化到数据库。我相信这是因为教义需要首先保留地址对象,以便它可以检索主要和& User对象中的外键关系。
$user = new User();
$address = new Address();
$this->getDoctrine()->getManager()->persist($address);
$this->getDoctrine()->getManager()->flush();
$address->setUser($user->setAddress($address));
$this->getDoctrine()->getManager()->persist($user);
$this->getDoctrine()->getManager()->flush();