php - 当表有两个枢轴和一个复合主键时,同步无法按预期工作
问题描述
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)。
解决方案
推荐阅读
- javascript - 成功将文件上传到MySQL中的字节数组,但是下载时内容不可读
- json - 如何将 json 数据关联到颤振列表?
- node.js - 在 Firebase 中部署函数时出错
- android - Kotlin 在与活动不同的布局上更新 textview 的文本
- javascript - 为什么我的快速路由器不响应我的获取请求?
- c# - C# 中的查询解析器
- postgresql - QueryDsl 按星期几聚合为地图
- c# - 创建新的 .Net Core 控制台进程:使用具有 UseShellExecute=true 的环境变量时出现异常
- python - 等号,关于 tensorflow 数据集,并没有真正为变量赋值
- html - Flexbox tailwind:不能让子元素的宽度调整内容