如何在父表中刪除記錄時在子表中設置parent_id = NULL?如何在父表中刪除記錄時在子表中設置parent_id = NULL?
這就像在MySQL的INNODB表中的ON DELETE = SET NULL,但我想避免在INNODB級別使用所有這些(級聯,忽略,更新和設置null)功能,並將其移動到atk4模型,以保持所有這一切邏輯一個地方。
例如,
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');
}
}
這按預期工作。 奇怪的是它看起來和我之前做的一樣(用foreach循環和save()方法),但是這個工作並且save()不用。 無論如何,這是真正回答上面問題的帖子,所以我會接受它。上面的其他帖子和評論也很有用 - 請檢查一下。 – DarkSide
您的解決方案將單獨加載每個條目,這將非常有效地利用SQL。 dsql()的使用速度要快得多。我可以問你在你自己的例子中嘗試這個:$ c-> set('parent_id',$ c-> dsql() - > expr('null'));', - 我只是好奇它是否會修理它。 – romaninsh
「null」的錯誤現在已修復,您可以再次編寫'$ c-> set('parent_id',null);'。 – romaninsh