我有两个实体User和UserProfile。 UserProfile primaryKey值不是AUTO_INCREMENT,它是使用User的主键值的一对一关系。当我创建新用户时出现错误:
App \ PublicBundle \ Entity \ User \ UserProfile类型的实体缺少字段' user'的已分配ID。此实体的标识符生成策略要求在调用EntityManager#persist()之前填充ID字段。如果您想要自动生成标识符,则需要相应地调整元数据映射。
问题是如何使用下一个数据库和实体结构保存实体:
用户DDL:
CREATE TABLE `user` (
`intUserID` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`intUserID`),
)
CREATE TABLE `user_profile` (
`intUserID` int(10) unsigned NOT NULL,
PRIMARY KEY (`intUserID`),
CONSTRAINT `user_profile_ibfk_1` FOREIGN KEY (`intUserID`) REFERENCES `user` (`intUserID`) ON DELETE CASCADE ON UPDATE CASCADE
)
用户实体:
/**
* @ORM\Table(name="user")
* @ORM\Entity
*/
class User
{
/**
* @var integer
*
* @ORM\Id
* @ORM\Column(name="intUserID", type="integer", nullable=false)
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $intuserid;
/**
* @var \App\PublicBundle\Entity\User\UserProfile
*
* @ORM\OneToOne(targetEntity="\App\PublicBundle\Entity\User\UserProfile",
* mappedBy="user",
* cascade={"persist", "remove"}
* )
*/
protected $profile;
}
UserProfile实体:
/**
* @ORM\Table(name="user_profile")
* @ORM\Entity
*/
class UserProfile
{
/**
* @var \App\PublicBundle\Entity\User\User
*
* @ORM\Id
* @ORM\OneToOne(targetEntity="\App\PublicBundle\Entity\User\User",
* inversedBy="profile"
* )
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="intUserID", referencedColumnName="intUserID")
* })
*/
protected $user;
}
注册操作
private function registration(Request $request, $tpl)
{
$user = new User();
$form = $this->$form($user, 'Create');
$form->handleRequest($request);
if ('POST' === $request->getMethod())
{
if ($form->isValid())
{
$em->getConnection()->beginTransaction();
try
{
$em = $this->getManager();
$em->persist($user);
$em->flush();
$this->sendSuccessEmail($user);
$em->getConnection()->commit();
}
catch (\Exception $e)
{
$em->getConnection()->rollback();
throw $e;
}
return $this->redirect($this->generateUrl('app_profile'));
}
}
return $this->render($tpl, array(
'entity' => $user,
'form' => $form->createView()
));
}
答案 0 :(得分:0)
正确的方法是,在持久化和刷新之前将其设置为空配置文件,并再次调用持久化和刷新:
注册操作
allow_url_fopen