I have 2 Models (SuperRubriques
and CustomRubriques
) using the same table rubriques
in DB.
When I delete from SuperRubriques
, I would like to delegate the delete to CustomRubriques
(as CustomRubriques
has a hasOne
association with extended_rubriques
that SuperRubriques
doesn't know).
For info, the rubriques
table in DB has the field model
containing 'CustomRubriques'
(i.e. the Model with which it has been saved).
I've tried to do it in SuperRubriquesTable::beforeDete()
:
// In SuperRubriquesTable.php
public function beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options)
{
$table = TableRegistry::getTableLocator()->get($entity->model); // $entity->model contains 'CustomRubriques'
$rubriqueEntity = $table->get($entity->id);
return $table->delete($rubriqueEntity);
}
However $table->delete($rubriqueEntity)
is true
(when I debug) but the record is not deleted in DB, I don't know why?
My Answer:
One possible reason why the record is not being deleted in the database could be due to the fact that the delete operation is being rolled back by the transaction management in CakePHP.
To ensure that the delete operation is successful, you can try disabling the transaction management for the delete operation in your beforeDelete method. Here's an updated version of your code:
php
// In SuperRubriquesTable.php
public function beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options)
{
$table = TableRegistry::getTableLocator()->get($entity->model); // $entity->model contains 'CustomRubriques'
$rubriqueEntity = $table->get($entity->id);
// Disable transaction management for the delete operation
$connection = $table->getConnection();
$connection->begin();
$result = $table->delete($rubriqueEntity);
$connection->commit();
return $result;
}
By disabling the transaction management and manually committing the delete operation, you can ensure that the record is successfully deleted in the database.
Rate this post
3 of 5 based on 5344 votesComments