I have two tables Groups and Tracking and they are connected. I wanna delete Groups records, and delete foreign key in Tracking, but i don't know how to delete or update into NULL value this foreign key. I don't wanna delete all records from Tracking. Any Idea? Thanks for help.
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();
}
In Tracking Table I have:
tr_id int PK,
tr_uId int FK,
tr_trtId int FK,
tr_trgId int FK,
tr_dateCreate data,
tr_status Char(1)
In TrackingGroups:
trg_Id int PK,
trg_name char(40),
trg_description char(256),
trg_uId int FK
How should delete works: when user want click delete button it should delete record from TrackingGroups and also it should delete or update field tr_trgId in Tracking table, there should be NULL value in tr_trgId.
Your idea is right, to find all tracking entries use find_all() function and then set tr_trgId to null and save them. Or you can achieve this in MySQL using 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();
}