diff --git a/src/Database/Concerns/HasRelationships.php b/src/Database/Concerns/HasRelationships.php index ecf581b9c..9d57f23df 100644 --- a/src/Database/Concerns/HasRelationships.php +++ b/src/Database/Concerns/HasRelationships.php @@ -326,6 +326,11 @@ protected function handleRelation($relationName) case 'belongsToMany': $relation = $this->validateRelationArgs($relationName, ['table', 'key', 'otherKey', 'parentKey', 'relatedKey', 'pivot', 'timestamps']); $relationObj = $this->$relationType($relation[0], $relation['table'], $relation['key'], $relation['otherKey'], $relation['parentKey'], $relation['relatedKey'], $relationName); + + if (isset($relation['pivotModel'])) { + $relationObj->using($relation['pivotModel']); + } + break; case 'morphTo': diff --git a/src/Database/Relations/Concerns/BelongsOrMorphsToMany.php b/src/Database/Relations/Concerns/BelongsOrMorphsToMany.php index 7e346d3d6..d7dffff39 100644 --- a/src/Database/Relations/Concerns/BelongsOrMorphsToMany.php +++ b/src/Database/Relations/Concerns/BelongsOrMorphsToMany.php @@ -119,9 +119,6 @@ public function create(array $attributes = [], array $pivotData = [], $sessionKe */ public function attach($id, array $attributes = [], $touch = true) { - $insertData = $this->formatAttachRecords($this->parseIds($id), $attributes); - $attachedIdList = array_pluck($insertData, $this->relatedPivotKey); - /** * @event model.relation.beforeAttach * Called before creating a new relation between models (only for BelongsToMany relation) @@ -136,14 +133,21 @@ public function attach($id, array $attributes = [], $touch = true) * }); * */ - if ($this->parent->fireEvent('model.relation.beforeAttach', [$this->relationName, $attachedIdList, $insertData], true) === false) { + if ($this->parent->fireEvent('model.relation.beforeAttach', [$this->relationName, $id, $attributes], true) === false) { return; } + $insertData = $this->formatAttachRecords($this->parseIds($id), $attributes); + $attachedIdList = array_pluck($insertData, $this->relatedPivotKey); + // Here we will insert the attachment records into the pivot table. Once we have // inserted the records, we will touch the relationships if necessary and the // function will return. We can parse the IDs before inserting the records. - $this->newPivotStatement()->insert($insertData); + if ($this->using) { + $this->attachUsingCustomClass($id, $attributes); + } else { + $this->newPivotStatement()->insert($insertData); + } if ($touch) { $this->touchIfTouching();