I’m after some code advice. I’ve got two models which are dependent on each other. When one of the models gets deleted I want to make sure both records in the database are deleted.
I handle this in one direction using foreign keys so if the parent gets deleted to. But as these rows are both dependent on each other I need the same functionality to happen in the child.
In the child model I’ve overloaded the delete method so it looks like this:
public function delete() {
$cameraTransaction = $this->dbConnection->beginTransaction();
try
{
$this->ftpuser->delete();
if($this->beforeDelete())
{
$result=$this->deleteByPk($this->getPrimaryKey())>0;
$this->afterDelete();
}
$cameraTransaction->commit();
}
catch(Exception $e) // an exception is raised if a query fails
{
$cameraTransaction->rollBack();
}
}
I’ve tested and this seems to work well. I wondered if an expert / guru could confirm whether I’ve done the right thing 🙂
Thanks
Alan
I think you are doing it right. You can make it something more general.
Every model has relations defined, make some(or all) the relations deletable. You have to flag them ( in someway) deletable along with current record.
I would define a new function besides
relations()in the model.and define some generic function (please include DB transactions in this function.)
And this generic function can be used any of your models.
Make sure that recursion does not happen here (i.e. parent deletes child … but child also tries to delete parent. )