2017-08-31 45 views
1

假設我有兩個實體collegedepartment大學有很多部門(一對多)。我validation.yml看起來像UniqueEntity驗證失敗 - Symfony?

App\CollegeBundle\Entity\College: 
     - departments: 
      - Valid: ~ 
App\CollegeBundle\Entity\Department: 
    constraints: 
     - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: 
      fields: [department_name, HOD ] 

當我試圖堅持與各部門Unique Entity驗證工作,後來當我試圖添加其他新department實體college實體,堅持unique entity驗證失敗的正數學院實體我得到unique key violation,我犯了什麼錯誤?

我使用CSV文件中的每一行csv import功能我在控制器做出一個Ajax調用例如

$department = new Department()  

if(isset($record["department_name"]) && strlen(trim($record["department_name"])) > 0) 
{ 
    $department->setDepartmentName($record["department_name"]); 
} 

if(isset($record["hod"]) && strlen(trim($record["hod"])) > 0) 
{ 
    $department->setHod($record["hod"]); 
} 

//set college 
$department->setCollege($college) 

//adding departments 
$college->addDepartment($department) 

$validate = $this->get('validator')->validate($college); 
if($validate->count()) 
{ 
    return [ "status" => "error" ] 
} 
else 
{ 
    $em = $this->getDoctrine()->getManager(); 
    $em->persist($college); 
    $em->flush(); 

    return [ "status" => "success" ]; 
} 
+1

請告訴我們代碼當你保存請 –

+0

@AlessandroMinoccheri我添加了代碼 –

回答

0

如果不創建一個新的學院(所以你已經大學實體)但只有一個新的部門試試這個:

//set college 
$department->setCollege($college) 

$validate = $this->get('validator')->validate($department); 
if($validate->count()) 
{ 
    return [ "status" => "error" ] 
} 
else 
{ 
    $em = $this->getDoctrine()->getManager(); 
    $em->persist($department); 
    $em->flush(); 

    return [ "status" => "success" ]; 
} 

相反,如果你正在創建一個新的大學我也建議你首先創建一個新的學院,堅持它和沖洗,以它的ID號,並創建新部門