1

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.

Community
  • 1
  • 1
  • possible duplicate, have a look to this post: http://stackoverflow.com/questions/9686888/how-to-truncate-a-table-using-doctrine-2 – Sylvain Martin Jan 07 '16 at 22:20
  • There is a small difference between the two posts. I'm looking for a method to truncate (or just delete all entries of) a table that is used in a many to many relation using only symfony and doctrine. Yet I find your link being very interesting. Thanks :) – George ȚUȚUIANU Jan 09 '16 at 09:17

2 Answers2

2

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.

craigh
  • 1,909
  • 1
  • 11
  • 24
  • The only problem with this solution would be that I don't have an entity created for my join table – George ȚUȚUIANU Jan 09 '16 at 09:08
  • I guess then you want to 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`. – craigh Jan 09 '16 at 13:38
  • Exactly. This is what I was looking for. I was hoping for something to let me delete all the entries for all the teams (like truncate) from a single query but this solution is the best until now. Thanks a lot! – George ȚUȚUIANU Jan 09 '16 at 14:23
  • I modified my answer above, if you wouldn't mind accepting. – craigh Jan 09 '16 at 15:16
1

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');
Richard
  • 4,079
  • 1
  • 14
  • 17
  • Indeed this would do the trick. I'm trying to keep a 'clean' implementation although if I won't find a solution I'll probably use your suggestion. Thanks :) – George ȚUȚUIANU Jan 07 '16 at 21:45
  • I like that someone took the time to -1 my answer. Where's a better solution then? :) – Richard Jan 08 '16 at 01:11