George ȚUȚUIANU
George ȚUȚUIANU

Reputation: 53

How can I remove all the entries from a many-to-many relation with symfony

I am working on a project where I need to have a registry of teams and tournaments. A team can be involved in many tournaments so is a many-to-many relation.

So in symfony I have only two entities created for this many-to-many relation: Teams and RgTournaments.

ERD

My question is how can I delete from a single query all current relations (truncate the table rg_teams_to_tournaments) using doctrine?

The only method I found is described here but I would like to avoid loading all the entries in order to delete them one by one.

Upvotes: 1

Views: 3182

Answers (2)

craigh
craigh

Reputation: 2291

Use DQL.

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#delete-queries

DELETE FROM RelatedEntity WHERE fk = :id

or you could use QueryBuilder to build the same basic idea

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html

If you do not have an actual entity, use the ->clear() method on the collection. You find the primary entity (e.g. Team) and then do like $myTeam->tournaments->clear(); and then flush.

Upvotes: 2

Richard
Richard

Reputation: 4119

You could just use raw SQL if all you want to do is blitz the entire table.

Quick/dirty but effective.

$entityManager->getConnection()->executeQuery('delete from your_many_to_many_join_table');

Upvotes: 1

Related Questions