I have realized that when user update his user_companies then two thing possible
1. He assign new companies to him
So i have to add it to user_companies table.
2. Remove companies from already assigned companies
So i have to delete other companies with this user.
Check my updaed code :
public function afterSave()
{
//Person Type user then it can insert user companies
if(!empty($_POST["user_companies"]) && $this->person_type == "user"){
foreach($_POST["user_companies"] as $val){
$UserCompanies = new UserCompanies;
$UserCompanies->person_id = $this->primaryKey;
$UserCompanies->company_id = $val;
if(!UserCompanies::model()->exists('person_id = :person_id && company_id = :company_id',
array(":person_id" => $this->primaryKey,
":company_id" => $val))){
$UserCompanies->save();
}
}
// while updating when user remove company from his/her old company so remove all comapnies that are not current selected companies of this person
UserCompanies::model()->deleteAll("person_id =".$this->primaryKey." && company_id NOT IN(".implode(",",$_POST["user_companies"]).")");
}else{
// Remove Companies from user_companies whenever user becomes person then it requires.
UserCompanies::model()->deleteAll("person_id =".$this->primaryKey);
}
parent::afterSave();
}