In CakePHP 3, suppose I want to delete all Departments that have some Employee named "John" (Departments have many Employees, Employees belongs to Department)
The easiest approach is to filter all those Departments, and delete them one by one in a foreach loop:
$departments = $this->Departments->find()
->matching('Employees', function ($q) {
return $q->where(['Employees.name' => 'John']);
})
->all();
foreach ($departments as $department) {
$this->Departments->delete($department);
}
This will result in one SELECT query plus one DELETE query for each record. I'd prefer one only query to be sent and executed by the database. Something like this:
DELETE Departments
FROM departments Departments
INNER JOIN employees Employees ON
Employees.department_id = Departments.id
AND Employees.name = 'John';
Reading the docs I find three ways to delete records:
- Using the Table object one by one, get the object, then delete it.
- Using the Table with deleteAll, which takes an array of conditions over the target table, not the associated ones.
- Using the ORM, again with only an array of conditions.
Is there an elegant way to obtain my query using CakePHP 3 and the ORM?