[英]How to delete child/child records in atk4?
看来ModelDeleteDelete挂钩在层次结构上不起作用。 让我举例说明。
class Model_User extends Model_Table{
public $table='user';
function init(){
parent::init();
$this->debug();
$this->addField('name');
$this->hasMany('Item');
$this->addHook('beforeDelete',$this);
}
function beforeDelete($m){
$m->ref('Item')->deleteAll();
}
}
class Model_Item extends Model_Table{
public $table='item';
function init(){
parent::init();
$this->debug();
$this->addField('name');
$this->hasOne('User');
$this->hasMany('Details');
$this->addHook('beforeDelete',$this);
}
function beforeDelete($m){
$m->ref('Details')->deleteAll();
}
}
class Model_Details extends Model_Table{
public $table='details';
function init(){
parent::init();
$this->debug();
$this->addField('name');
$this->hasOne('Item');
}
}
当我在“祖父母” Model_User上调用delete()时,它将尝试按预期删除所有Item记录,但是从那里不执行Item.beforeDelete挂钩,并且在尝试删除Item之前不要删除Details记录。
我做错了什么?
我想至少在分层模型结构中它有效。
这是这样做的:
class Model_Object extends hierarchy\Model_Hierarchy {
public $table = 'object';
function init(){
parent::init();
$this->debug(); // for debugging
$this->addField('name');
$this->addHook('beforeDelete',$this);
}
function beforeDelete($m) {
// === This is how you can throw exception if there is at least one child record ===
// if($m->ref('Object')->count()->getOne()) throw $this->exception('Have child records!');
// === This is how you can delete child records, but use this only if you're sure that there are no child/child records ===
// $m->ref('Object')->deleteAll();
// === This is how you can delete all child records including child/child records (hierarcialy) ===
// Should use loop if we're not sure if there will be child/child records
// We have to use newInstance, otherwise we travel away from $m and can't "get back to parent" when needed
$c = $m->newInstance()->load($m->id)->ref('Object');
// maybe $c = $m->newInstance()->loadBy('parent_id',$m->id); will work too?
foreach($c as $junk){
$c->delete();
}
return $this;
}
}
重要的事情是:
*扩展层次结构\\ Model_Hierarchy类而不是Model_Table
*在beforeDelete挂钩中使用适当的方法
* *如果我们有孩子则限制删除-抛出异常
* * deleteAll-当您确定没有子记录时使用它
* * newInstance +循环+删除-在必须删除记录(甚至子级/子级...)时使用它
也许有些人有更好的解决方案?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.