Skip to content

Commit

Permalink
Updated readme
Browse files Browse the repository at this point in the history
  • Loading branch information
korridor committed Mar 1, 2024
1 parent 2a94e22 commit ca562d4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
26 changes: 25 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.

Expand Down
3 changes: 1 addition & 2 deletions tests/HasManySyncTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit ca562d4

Please sign in to comment.