首页 > 解决方案 > 当表有两个枢轴和一个复合主键时,同步无法按预期工作

问题描述

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)。

标签: phplaravellaravel-5

解决方案


推荐阅读