문제

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

도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top