问题
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 ?
My User entity :
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;
...
}
My Project entity:
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;
...
}
EDIT TO RESPONSE FractalizeR :
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();
...
}
}
Do you mean I have to set manually the usernameCanonical property after the persist ? Or where/when ? But especially how ?
回答1:
When you're creating an instance of Structure
and then trying to persist/flush... Doctrine2 is:
- 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)
What you must do is...
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).
来源:https://stackoverflow.com/questions/8009406/the-good-way-to-persist-a-fosuser-entity-in-cascade