2014-09-20 45 views
0

我的代碼中有以下片段,但問題是當我嘗試添加多個項目時。它正在被添加,但它正在重新添加以前添加的行,例如: - 在下面的代碼片段中,只有一條記錄會出現在ID爲150的位置,並且該記錄將是13.您能否告訴我問題是什麼。Kohana/PHP記錄被替換,如果它在循環內運行

public function StoreSkills($skills,$id) { 
    $skills = "16,13"; 
    $id = "150"; 
    if(!empty($skills)){ 
     $UserSkillsObj = ORM::factory('userskill'); 
    $userskills = explode(',',$skills); 
    foreach($userskills as $skill) 
    { 
     // $UserSkillsObj = ORM::factory('userskill'); if this statement is here, 
               //records are getting added just fine. 
     $UserSkillsObj->user_id = $id; 
     $UserSkillsObj->skills_id = $skill; 
     $ids = $UserSkillsObj->save(); 


    } 
    } 

} 

回答

1

將創建對象的線移動到您的foreach循環中。外面有它意味着你總是引用相同的對象,因此最後的(第二)環路可節省超過第一位的,使得它總是13

例子:

foreach($userskills as $skill) 
{ 
    $UserSkillsObj = ORM::factory('userskill'); 
    $UserSkillsObj->user_id = $id; 
    $UserSkillsObj->skills_id = $skill; 
    $ids = $UserSkillsObj->save(); 
}