n : m 관계가 필요합니다. 따라서 한 직원을 여러 부서에 할당하고 한 부서에는 많은 직원이 할당 될 수 있습니다.
tbl_employee (ID, 이름, 나이, 등) (employee_id입니다, department_id) tbl_department (ID, 이름 tbl_employee_department : 는 당신이 필요로하는 것은 다음과 같은 하나 개 이상의 부서에 직원을 연결하는 소위 피벗 테이블 등)
는 이제 직원의 관계는 다음과 같이 보일 것이다 :
public function relations()
{
return array(
'employees' => array(self::MANY_MANY, 'Employee', 'tbl_employee_department(employee_id, department_id)'),
);
}
012 : 같을 것이다
public function relations()
{
return array(
'departments' => array(self::MANY_MANY, 'Department', 'tbl_employee_department(employee_id, department_id)'),
);
}
그리고 부서 관계를
이제 $ employee-> departments는 여러 부서 모델의 배열을 반환합니다. 그러나 당신이 양식에 대해 원하는 것은 arrayof 부서 식별자입니다, 그래서 당신은
public $departmentIds=array();
public function afterFind()
{
if(!empty($this->departments)) {
foreach($this->departments as $id=>$department)
$this->departmentIds[]=$department->id;
}
parent::afterFind();
}
public function afterSave()
{
$tx = Yii::app()->db->beginTransaction();
try {
//delete all connections from this employee to any department first
$command = Yii::app()->db->createCommand();
$command->delete('tbl_employee_department', 'employee_id=:id', array(':id'=>$this->id));
//now reconnect the employee to the departments in the departmentIds array
foreach($this->departmentsIds as $id) {
$command = Yii::app()->db->createCommand();
$command->insert('tbl_employee_department', array(
'employee_id' => $this->id,
'department_id'=> (int)$id
));
}
$tx->commit();
} catch (Exception $e) {
$tx->rollback();
throw new CException('Something bad happend. Cancelled transaction and rolled back data! '.$e->getMessage());
}
parent::afterSave();
}
이 코드는 데이터베이스에서 부서를 가져와 당신 자마자 $ departmentIds 배열에서 자신의 ID를 저장하여 직원 모델에서이 작업을 수행해야 Employee :: model() -> find() 등을 통해 데이터베이스에서 직원 모델을 가져온다. $ employee-> save()를 호출하고 저장 프로세스가 성공하면 afterSave 메소드가 호출됩니다. 그런 다음이 직원과 그가 할당 된 모든 부서 간의 모든 연결을 삭제 한 트랜잭션을 시작한 다음 departmentIds 배열에 저장된 모든 부서를 추가합니다.당신은 당신이 안전 선언해야합니다) $ 모델 -> setAttributes (를 통해이 분야를 설정하려면
당신의 직원 규칙이 넣어 (그래서 YII는 대량 할당 할 수 있습니다)
public function rules()
{
return array(
//...all the other rules...
array('departmentIds', 'safe'),
);
}
아시다시피, 꽤 복잡해 보입니다.하지만 제 생각에는 그 아이디어가 있어야합니다. 왼쪽의 유일한 문제는 양식을 통해 departmentIds 배열의 ID를 설정하는 것입니다.하지만이를 수행하기 위해 texfield 문자열을 분해 할 수 있습니다.이게 그렇게 어렵지는 않습니다.
위의 변경을 시도했습니다. 피벗 테이블 이름을 EmployeeDepts로 수정했습니다. 나는 오류가 발생했습니다 : ** 'departments.EmployeeDepts (employeeId'in 'where 절'실행 된 SQL 문은 SELECT \'departments \'. \'id \ 'AS \'t1_c0 \', \'departments \ (EmployeeDepts (employeeId \'= : ypl0) AND (\'departments \') '와 같은) . \'departmentId) \'= : ypl1) ** – jcsbrotha
내 관계는 다음과 같이 보입니다 :' 'departments'=> 배열 (self :: HAS_MANY, 'Department', 'EmployeeDepts (employeeId, departmentId)')' – jcsbrotha
그것은 테이블을 다른 테이블로 인식하지 못하는 것 같지만 부서 테이블을 사용하는 대신 올바른 테이블을 가리키는 방법은 무엇입니까? – jcsbrotha