Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Database/Concerns/HasRelationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -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':
Expand Down
14 changes: 9 additions & 5 deletions src/Database/Relations/Concerns/BelongsOrMorphsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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();
Expand Down