级联更新或删除 - kohana

时间:2016-09-15 08:40:08

标签: php kohana-3 kohana-orm kohana-3.2 kohana-3.3

我有两个表组和跟踪,它们已连接。我想删除组记录,并删除跟踪中的外键,但我不知道如何删除或更新此值的外键值。我不想删除跟踪中的所有记录。任何的想法?谢谢你的帮助。

 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();

    } 

在跟踪表中我有:

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

在TrackingGroups中:

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

删除应该如何工作:当用户想要点击删除按钮时,它应该从TrackingGroups中删除记录,并且它应该删除或更新Tracking表中的字段tr_trgId,tr_trgId中应该有NULL值。

1 个答案:

答案 0 :(得分:1)

您的想法是正确的,找到所有跟踪条目使用find_all()函数,然后将tr_trgId设置为null并保存它们。 或者你可以在MySQL中使用Forign键事件在Tracking表中删除set 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_all() as $tracking){
           $tracking->tr_trgId= null;
           $tracking->save();
        }

        parent::delete();

    }