How to set parent_id=NULL in child table when record in parent table is deleted?
It’s like ON DELETE = SET NULL in MySQL INNODB tables, but I would like to avoid using all this (cascading, ignoring, updating and setting null) functionality in INNODB level and move it to atk4 Model to keep all this in logic one place.
For example,
class Model_Parent extends Model_Table{
public $table='parent';
function init(){
parent::init();
$this->addField('name');
$this->hasMany('Child');
$this->addHook('beforeDelete',$this);
}
function beforeDelete($m){
// I guess here I should somehow set parent_id=NULL in all related Model_Child
// records, but when I do so, then it's again DB constraint violation of course
$c = $m->ref('Child');
foreach($c as $junk){
$c->set('parent_id',NULL); // this and below is not working
$c->save();
}
}
}
class Model_Child extends Model_Table{
public $table='child';
function init(){
parent::init();
$this->addField('name');
$this->hasOne('Parent');
}
}
It’s simple, you just need to go into DSQL from Model:
More info: http://www.youtube.com/watch?v=sSRaYpoJFHk&list=PL7CBF92AB03A1CA3B&index=3&feature=plpp_video