级联更新或删除 - kohana

Cascade Update or Delete - kohana

我有两个 tables 组和跟踪,它们已连接。我想删除Groups记录,并删除Tracking中的外键,但我不知道如何删除或更新这个外键为NULL值。我不想从跟踪中删除所有记录。任何的想法?感谢您的帮助。

 protected $_table_name = 'trackingGroup';
 protected $_primary_key = 'trg_id';

protected $_has_many = array(
    'tracking' => array(
        'model' => 'Orm_tracking',
        'foreign_key' => 'tr_trgId',
    ),
);
 protected $_belongs_to = array(
    'user' => array(
        'model' => 'Orm_users',
        'foreign_key' => 'trg_uId',
    ),
);

function delete(){ //my first idea
        foreach($this->tracking->tr_trtId->find() as $tracking)
            $tracking->delete();
        parent::delete();

    } 

在跟踪中 Table 我有:

tr_id int PK,
tr_uId int FK,
tr_trtId int FK,    
tr_trgId int FK,
tr_dateCreate data,
tr_status Char(1)

在跟踪组中:

trg_Id int PK,
trg_name char(40),
trg_description char(256),
trg_uId int FK

删除应该如何工作:当用户想要单击删除按钮时,它应该从 TrackingGroups 中删除记录,还应该删除或更新跟踪 table 中的字段 tr_trgId,[ 中应该有 NULL 值=21=].

你的想法是对的,找到所有跟踪条目使用find_all() 函数然后将tr_trgId 设置为空并保存它们。 或者,您可以在 MySQL 中使用 Forign key events ON delete set null in Tracking table 来实现。

protected $_table_name = 'trackingGroup';
 protected $_primary_key = 'trg_id';

protected $_has_many = array(
    'tracking' => array(
        'model' => 'Orm_tracking',
        'foreign_key' => 'tr_trgId',
    ),
);
 protected $_belongs_to = array(
    'user' => array(
        'model' => 'Orm_users',
        'foreign_key' => 'trg_uId',
    ),
);

function delete(){ 
         //my first idea
        foreach($this->tracking->tr_trtId->find_all() as $tracking){
           $tracking->tr_trgId= null;
           $tracking->save();
        }

        parent::delete();

    }