问题描述
我想要保留一个用户实体扩展FOSUserBundle实体,但发生错误:
I want to persist a User entity extends FOSUserBundle entity but an error occured :
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'username_canonical' cannot be null
如何重载我的用户实体的持久化功能给出需要的信息?
How can I overload the persist function of my User entity to give the informations it needs ?
我的用户实体:
class User extends BaseUser
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
*
* @ORM\OneToOne(targetEntity="MyApp\MainBundle\Entity\Project")
*/
private $project;
...
}
我的项目实体:
class Structure
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var integer $master
*
* @ORM\OneToOne(targetEntity="Uriae\UserBundle\Entity\User", cascade={"persist"})
*
* @Assert\NotBlank()
* @Assert\Type(type="Uriae\UserBundle\Entity\User")
*/
private $master;
...
}
编辑回复FractalizeR:
EDIT TO RESPONSE FractalizeR :
你的意思是我必须手动设置usernameCanonical属性后坚持吗?
Do you mean i must set manually the usernameCanonical property after the persist ?
积极地在表单发送后我的控制器:
Actyally i have that after the form is sent in my controller :
$structure = new \Uriae\MainBundle\Entity\Structure();
if ($request->getMethod() == 'POST')
{
$form->bindRequest($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getEntityManager();
$em->persist($structure);
$em->flush();
...
}
}
你的意思是我必须手动设置usernameCanonical属性后坚持吗?或何时/何时?但是特别是如何?
Do you mean I have to set manually the usernameCanonical property after the persist ? Or where/when ? But especially how ?
推荐答案
创建结构
然后尝试持续/冲洗... Doctrine2是:
When you're creating an instance of Structure
and then trying to persist/flush... Doctrine2 is:
- 意识到
结构之间存在关系
与用户
(每个结构
实例必须有一个/ code>实例)
- 因为没有
用户
明确绑定到code>实例,它尝试创建一个空的。
-
User
上的保存操作失败,因为有没有数据(在这种情况下,usernameCanonical字符串为空)
- Realising that there is a relationship on
Structure
withUser
(eachStucture
instance must have aUser
instance) - Because there is no
User
explicitly bound to theStructure
instance, it tries to create an empty one. - The save operation on the
User
fails, because there is no data (in this case, usernameCanonical string is empty)
您必须做的是...
在保存结构
之前,添加一个用户
的实例...如果您要使用当前用户,则使用此
Before you save the Structure
, add an instance of User
to it... if you want to use the current user then use this
$user = $this->get('security.context')->getToken()->getUser();
$structure->setMaster($user);
$em->persist($structure);
$em->flush();
请记住,将用户
实体包含在您的控制器类(使用使用
语句)。
Remember to include the User
entity in your controller class (with the use
statement).
这篇关于保持FOSUser实体级联的好办法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!