Question

I have Apparel and User classes. Each user can have many apparels. And apparel can be belong to only one User

class Apparel
{
    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="apparels", cascade={"persist"})
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
     */
    private $user;    
}


class User 
{
    /**
     * @ORM\OneToMany(targetEntity="Apparel", mappedBy="user")
     */
    private $apparels;
}

The problem is that new user are added to database when I'm updating.

  • What is wrong with my code?

Here's my Controller

$user = $this->get('session')->get('user');
$apparel->setUser($user);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($apparel);
$entityManager->flush();

enter image description here

Was it helpful?

Solution

My guess is that the reason a new user is being created is because you are working with an object that is not being managed by Doctrine and probably allowing cascade creation.

So my recommendation would be to get the User Id from the session and try,

$user = $userRepository->find($userId) 

and then call,

$apparel->setUser($user);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top