CakePHP deleteAll for many, many relationships does not delete connection records

I'm on CakePHP v3.17 w / Postgres 9.4

I am trying to get $this->SomeTable->deleteAll([...]) to delete entries in the connection table.

Display system with table for Stops and table for Routes . Stops are associated with many routes (since several bus routes can stop on each route), and routes are obviously associated with many stops.

RoutesTable.php:

 $this->belongsToMany('Stops'); 

StopsTable.php:

 $this->belongsToMany('Routes'); 

Here's the deletion logic that I want to use, but DOES NOT work, because the entries in the join table remain:

  $stopsTable = TableRegistry::get('Stops'); $stopsTable->deleteAll(['agency_id' => $agency->id]); $routesTable = TableRegistry::get('Routes'); $routesTable->deleteAll(['agency_id' => $agency->id]); 

Here is the logic that works, but is inefficient, because it has to iterate over each stop:

  $stopsTable = TableRegistry::get('Stops'); foreach ($agency->stops as $stop) { $stopsTable->delete($stop); } $routesTable = TableRegistry::get('Routes'); $routesTable->deleteAll(['agency_id' => $agency->id]); 

What is the best / right way to do this?

Here's a similar question , but for v2.x, so not necessarily here.

+5
source share
1 answer

There is no way to do what you need. But I would, of course, propose to do what you already said in your discovery and wrap it with a transaction (note that this has not been verified, but should work):

 $stopsTable->connection()->transactional(function () use ($stopsTable, $stops) { foreach ($stops as $stop) { $stopsTable->delete($stop); } }); 
+1
source

Source: https://habr.com/ru/post/1247455/


All Articles