以下作品和一行插入到两个表中:
$user = new User();
$user->setId(8484);
$user->setData("user test data");
$profile = new Profile();
$profile->setBlah(8484);
$profile->setData("profile test data");
// if I leave this out it works...
$user->setProfile($profile);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->flush();
但是如果省略$user->setProfile($profile);
我会得到一个错误,因为User
' 的 id 为空:
An exception occurred while executing 'INSERT INTO User (id, data) VALUES (?, ?)' with params {"1":null,"2":"user test data"}
怎么可能?
class User
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\Column(type="string", length=64)
*/
protected $data;
/**
* @ORM\OneToOne(targetEntity="Profile", cascade={"persist", "remove"})
* @ORM\JoinColumn(name="id", referencedColumnName="blah")
*/
protected $profile;
}
class Profile
{
/**
* @ORM\Id
* @ORM\Column(name="blah", type="integer")
*/
protected $blah;
/**
* @ORM\Column(type="string", length=64)
*/
protected $data;
}
设置 Profile 方法:
/**
* Set Profile
*
* @param \Test\AdminBundle\Entity\Profile $profile
* @return User
*/
public function setProfile(\Test\AdminBundle\Entity\Profile $profile = null)
{
$this->profile = $profile;
return $this;
}
编辑:
如果我将 joinColumn 名称更改为随机名称,我的对象使用 var_dump 看起来正确,但查询失败:
/**
* @ORM\OneToOne(targetEntity="Profile", cascade={"persist"})
* @ORM\JoinColumn(name="random_test", referencedColumnName="blah")
*/
给出:
An exception occurred while executing 'INSERT INTO User (id, data, random_test) VALUES (?, ?, ?)' with params {"1":8484,"2":"user test data","3":null}: