持久化时,Doctrine @id为null

时间:2013-03-22 10:04:09

标签: symfony doctrine

以下工作和插入两个表的行:

$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为null:

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;
}

设置个人资料方法:

/**
 * Set Profile
 *
 * @param \Test\AdminBundle\Entity\Profile $profile
 * @return User
 */
public function setProfile(\Test\AdminBundle\Entity\Profile $profile = null)
{
    $this->profile = $profile;

    return $this;
}

修改

如果我使用var_dump将joinColumn名称更改为随机,我的对象看起来正确,但查询失败:

/**
 * @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}:

1 个答案:

答案 0 :(得分:1)

在Doctrine成功建立用户与个人资料之间的关系之前,您需要保留您的$个人资料。

$em = $this->getDoctrine()->getEntityManager();    

$user = new User();
$user->setId(8484);
$user->setData("user test data");

$profile = new Profile();
$profile->setBlah(8484);
$profile->setData("profile test data");
$em->persist($profile);

$user->setProfile($profile); 
$em->persist($user);
$em->flush();

想想你在MySQL代码中想要做什么。

原来你说的是:

插入用户的个人资料(8484)

导致(错误:配置文件8484不存在)。

你想说的是:

插入个人资料(8484)。 插入个人资料为(8484)的用户。

相关问题