Thomas
Thomas

Reputation: 143

Symfony 3 - delete rows on intermediate table manyToMany

My problem : I have an entity User and an entity Skill. A user can have multi skills, and a skill can have multi users, so i have a relation ManyToMany on this. The result is a third intermediate table called "Users_Skills" with columns user_id and skill_id.

I want to delete rows on this table, by example all rows where id_user = 5.

I don't know how to do this, because I have no entity for the table Users_Skills, and no repository. What is th best way to do this ?

Upvotes: 0

Views: 324

Answers (2)

Vamsi Krishna B
Vamsi Krishna B

Reputation: 11490

generally when working with Doctrine ORM, you should think in terms of Objects and not in terms of tables and rows.

$user = $em->getRepository('AppBundle:User')->find(5);
$skills = $user->getSkills();

foreach ($skills as $skill)
{
    $user->removeSkill($skill);
}

$em->flush();

Another option

$user = $em->getRepository('AppBundle:User')->find(5);
$skills = $user->getSkills();
$skills->clear();
$em->flush();

Also do read about Owning Side and Inverse Side

Upvotes: 1

Terenoth
Terenoth

Reputation: 2598

You just need to get your User entity with the id 5, to empty his list of skills, then persist and flush.

Example (in a controller):

$id = 5;
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository(User::class);
$user = $repository->find($id);
$user->setSkills([]);
$em->flush();

Upvotes: 0

Related Questions