2012-08-08 163 views
1

看起來,模型鉤beforeDelete不工作層次結構。 讓我來舉例說明。如何刪除atk4中的子/記錄?

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,然後它會嘗試刪除所有記錄項如預期,但是從那裏不執行Item.beforeDelete鉤不要刪除詳細記錄在嘗試刪除Item之前。

我在做什麼錯了?

回答

1

我想我得到它至少爲分層模型結構工作。

這是它是怎麼做:

這裏
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 + loop + delete - 當您必須刪除時使用它e記錄(甚至是孩子/孩子/ ...)hierarchialy

也許你們有些人有更好的解決方案?

+0

弗雷德我仍然在4.1,所以無法添加任何東西。可能是4.2中的一個錯誤,它不會級聯刪除,但羅馬人應該能夠驗證。 – 2012-08-09 13:20:20