|
10 | 10 | trait InteractsWithPivotTable |
11 | 11 | { |
12 | 12 | /** |
| 13 | + * The cached copy of the currently attached pivot models. |
| 14 | + * |
13 | 15 | * @var Collection |
14 | 16 | */ |
15 | | - private $current; |
| 17 | + private $currentlyAttached; |
16 | 18 |
|
17 | 19 | /** |
18 | 20 | * Toggles a model (or models) from the parent. |
@@ -94,7 +96,8 @@ public function sync($ids, $detaching = true) |
94 | 96 | // First we need to attach any of the associated models that are not currently |
95 | 97 | // in this joining table. We'll spin through the given IDs, checking to see |
96 | 98 | // if they exist in the array of current ones, and if not we will insert. |
97 | | - $current = $this->getCurrent()->pluck($this->relatedPivotKey)->all(); |
| 99 | + $current = $this->getCurrentlyAttachedPivots() |
| 100 | + ->pluck($this->relatedPivotKey)->all(); |
98 | 101 |
|
99 | 102 | $detach = array_diff($current, array_keys( |
100 | 103 | $records = $this->formatRecordsList($this->parseIds($ids)) |
@@ -217,7 +220,7 @@ public function updateExistingPivot($id, array $attributes, $touch = true) |
217 | 220 | */ |
218 | 221 | protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch) |
219 | 222 | { |
220 | | - $updated = $this->getCurrent() |
| 223 | + $updated = $this->getCurrentlyAttachedPivots() |
221 | 224 | ->where($this->foreignPivotKey, $this->parent->{$this->parentKey}) |
222 | 225 | ->where($this->relatedPivotKey, $this->parseId($id)) |
223 | 226 | ->first() |
@@ -465,6 +468,20 @@ protected function detachUsingCustomClass($ids) |
465 | 468 | return $results; |
466 | 469 | } |
467 | 470 |
|
| 471 | + /** |
| 472 | + * Get the pivot models that are currently attached. |
| 473 | + * |
| 474 | + * @return \Illuminate\Support\Collection |
| 475 | + */ |
| 476 | + protected function getCurrentlyAttachedPivots() |
| 477 | + { |
| 478 | + return $this->currentlyAttached ?: $this->newPivotQuery()->get()->map(function ($record) { |
| 479 | + $class = $this->using ? $this->using : Pivot::class; |
| 480 | + |
| 481 | + return (new $class)->setRawAttributes((array) $record, true); |
| 482 | + }); |
| 483 | + } |
| 484 | + |
468 | 485 | /** |
469 | 486 | * Create a new pivot model instance. |
470 | 487 | * |
@@ -645,18 +662,4 @@ protected function getTypeSwapValue($type, $value) |
645 | 662 | return $value; |
646 | 663 | } |
647 | 664 | } |
648 | | - |
649 | | - /** |
650 | | - * Get the existing records. |
651 | | - * |
652 | | - * @return \Illuminate\Support\Collection |
653 | | - */ |
654 | | - protected function getCurrent() |
655 | | - { |
656 | | - return $this->current ?: $this->newPivotQuery()->get()->map(function ($record) { |
657 | | - $class = $this->using ? $this->using : Pivot::class; |
658 | | - |
659 | | - return (new $class)->setRawAttributes((array) $record, true); |
660 | | - }); |
661 | | - } |
662 | 665 | } |
0 commit comments