From 966edea734a0e330f19ebe2547a1332ed39cb907 Mon Sep 17 00:00:00 2001 From: Luke Towers Date: Mon, 24 Oct 2022 12:10:13 -0600 Subject: [PATCH] Set pivot data when initially syncing the relationship Also performs the sync with model instances rather than just raw IDs to support relationships with a custom relatedKey set (the key on the related model's table that is stored on the pivot table to connect the relationship, normally just the primary key but can be anything). --- modules/backend/behaviors/RelationController.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/backend/behaviors/RelationController.php b/modules/backend/behaviors/RelationController.php index 9e0f221ed8..899a36b0fd 100644 --- a/modules/backend/behaviors/RelationController.php +++ b/modules/backend/behaviors/RelationController.php @@ -1392,14 +1392,15 @@ public function onRelationManagePivotCreate() * Add the checked IDs to the pivot table */ $foreignIds = (array) $this->foreignId; - $this->relationObject->sync($foreignIds, false); + $saveData = $this->pivotWidget->getSaveData(); + $foreignModels = $this->relationModel->whereIn($this->relationModel->getKeyName(), $foreignIds)->get(); + $this->relationObject->syncWithPivotValues($foreignModels, $saveData['pivot'] ?? []); /* * Save data to models */ $foreignKeyName = $this->relationModel->getQualifiedKeyName(); $hydratedModels = $this->relationObject->whereIn($foreignKeyName, $foreignIds)->get(); - $saveData = $this->pivotWidget->getSaveData(); foreach ($hydratedModels as $hydratedModel) { $modelsToSave = $this->prepareModelsToSave($hydratedModel, $saveData);