The good way to persist a FOSUser entity in cascade

帅比萌擦擦* 提交于 2019-12-09 13:46:19

问题


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:

  1. Realising that there is a relationship on Structure with User (each Stucture instance must have a User instance)
  2. Because there is no User explicitly bound to the Structure instance, it tries to create an empty one.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!