From ca562d41e744851b68d1baf93476e2ff575fcce1 Mon Sep 17 00:00:00 2001 From: korridor <26689068+korridor@users.noreply.github.com> Date: Fri, 1 Mar 2024 14:27:18 +0100 Subject: [PATCH] Updated readme --- README.md | 26 +++++++++++++++++++++++++- tests/HasManySyncTest.php | 3 +-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 83319e8..72f5d1f 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ $customer->contacts()->sync([ ]); ``` -The sync method accepts an array of data to place on the intermediate table. Any data that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the data in the given array will exist in the intermediate table: +The sync method accepts an array of data to place on the intermediate table. Any data that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the data in the given array will exist in the intermediate table. #### Syncing without deleting @@ -86,6 +86,30 @@ $customer->contacts()->sync([ ], false); ``` +#### Behaviour for IDs that are not part of the hasMany relation + +If an ID in the related data does not exist or is not in the scope of the `hasMany` relation, the `sync` function will throw a `ModelNotFoundException`. +It is possible to modify this behavior with the `$throwOnIdNotInScope` attribute. Per default, this is set to `true`. If set to false, the `sync` function will ignore the Ids instead of throwing an exception. + +```php +$customer->contacts()->sync([ + [ + 'id' => 7, // ID that belongs to a different customer than `$customer` + 'name' => 'Peter', + 'phone_number' => '321', + ], + [ + 'id' => 1000, // ID that does not exist + 'name' => 'Alfa', + 'phone_number' => '123', + ], + [ + 'id' => null, + 'name' => 'Adhitya', + 'phone_number' => '234, + ] +], throwOnIdNotInScope: false); +``` #### Example usage in the controller. diff --git a/tests/HasManySyncTest.php b/tests/HasManySyncTest.php index 2bac3c9..134cd4c 100644 --- a/tests/HasManySyncTest.php +++ b/tests/HasManySyncTest.php @@ -6,7 +6,6 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\ModelNotFoundException; -use Illuminate\Foundation\Testing\RefreshDatabase; use Korridor\LaravelHasManySync\Tests\TestEnvironment\Models\Task; use Korridor\LaravelHasManySync\Tests\TestEnvironment\Models\User; @@ -272,7 +271,7 @@ public function testUpdateOnIdThatDoesNotBelongToRelationIgnoresTheEntryWithProb 'content' => 'Updated Task 3 of Tester 2', ] // Delete, because task with id=1 is missing - ], true, false); + ], throwOnIdNotInScope: false); } catch (\Throwable $throwable) { // Assert $this->fail();