Skip to content
This repository has been archived by the owner on Sep 22, 2024. It is now read-only.

Update BelongsToMany.php #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
24 changes: 15 additions & 9 deletions src/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ class BelongsToMany extends BaseBelongsToMany
*/
public function attach($id, array $attributes = [], $touch = true)
{
$this->parent->setPivotChanges('attach', $this->getRelationName(), [
$this->parseId($id) => $attributes,
]);
$idsWithAttributes = collect($id)->mapWithKeys(function ($id) use ($attributes) {
return [$id => $attributes];
})->all();

$this->parent->setPivotChanges('attach', $this->getRelationName(), $idsWithAttributes);

if ($this->parent->firePivotAttachingEvent() === false) {
return false;
Expand All @@ -42,23 +44,27 @@ public function attach($id, array $attributes = [], $touch = true)
*/
public function detach($ids = null, $touch = true)
{
$resultIds = [];
if (is_null($ids)) {
$ids = $this->query->pluck(
$this->query->qualifyColumn($this->relatedKey)
)->toArray();
$resultIds = $this->query->pluck($this->query->qualifyColumn($this->relatedKey))->toArray();
}

$idsWithAttributes = collect($ids)->mapWithKeys(function ($id) {
$idsWithAttributes = collect($resultIds)->mapWithKeys(function ($id) {
return [$id => []];
})->all();

$this->parent->setPivotChanges('detach', $this->getRelationName(), $idsWithAttributes);

if ($this->parent->firePivotDetachingEvent() === false) {
return false;
}

$result = parent::detach($ids, $touch);
if ($ids === null) {
$result = parent::detach(null, $touch);
}
if ($ids !== null) {
$result = parent::detach($ids, $touch);
}

$this->parent->firePivotDetachedEvent();

Expand Down