当表格具有两个枢轴和一个复合主键时,同步无法正常工作

时间:2018-10-11 12:40:10

标签: php laravel laravel-5

class ProjectEmployees extends Migration
{

    public function up()
    {

        // employees assigned to each project
        Schema::create('project_employees', function (Blueprint $table) {
            $table->integer("project_id")->unsigned();
            $table->integer("employee_id")->unsigned();
            $table->tinyInteger("is_project_leader")->unsigned()->default(0);
            $table->tinyInteger("is_manager")->unsigned()->default(0);
        });


        Schema::table('project_employees', function($table) {


            $table->primary(['project_id', 'employee_id']);

            // FK
            $table->foreign('employee_id')->references('id')->on('employees');
            $table->foreign('project_id')->references('id')->on('projects');
        });

    }

}

我有一个项目模型,另一个是雇员模型。我希望能够将员工分配为项目负责人和项目经理。我有这种方法:

 function assignProjectLeaders($project, $employees)
    {    
        $syncData = $this->addPivotValue($employees, ['is_project_leader' => true]);
        $project->projectLeaders()->sync($syncData);           
    }

function addPivotValue($items, $pivotValues): array
{
    $pivotData = array_fill(0, count($items), $pivotValues);
    $syncData = array_combine($items, $pivotData);
    return $syncData;
}

因此,我希望方法AssignProjectLeaders将给定的雇员设置为给定项目对象的项目负责人。但是,如果已经有一名雇员作为项目经理与该项目相关联,则由于主键限制(它似乎试图再次插入该对(项目,雇员),而不是仅将is_project_leader列更新为1),这将无法正常工作。 / p>

0 个答案:

没有答案