I have some relations:
public function handleServices(array $services): bool
{
$allServicesId = $this->services()->get(['service_id'])->pluck('service_id')->toArray();
return ManyToManyHelper::manageRelations($this->services(), $allServicesId, $services);
}
There I use ManyToManyHelper
class ManyToManyHelper
{
public static function manageRelations(BelongsToMany $relation, array $allIds, array $manageIds): bool
{
try {
foreach ($manageIds as $categoryId) {
if (!in_array($categoryId, $allIds)) {
$relation->attach($categoryId);
}
}
$toDeleteIds = array_diff($allIds, $manageIds);
if (count($toDeleteIds) > 0) {
$relation->detach($toDeleteIds);
}
return true;
} catch (Exception $exception) {
return false;
}
}
}
But I try to use Syncing Associations
- https://laravel.com/docs/9.x/eloquent-relationships#syncing-associations
And I don't understand at all how to change Many to Many
to sync
.
Can I get any example?
I have one example (https://www.scratchcode.io/source-books/laravel-sync-with-an-example/) but It doesn't give me success
CodePudding user response:
You can do:
public function handleServices(array $services): bool {
$this->services()->sync($services);
return true;
}
This will ensure that all ids listed in $services
and only those ids are associated with $this
model's services
relationship. This is assuming that $this
is a model and $services
has the list of ids that you want to strictly associate.
CodePudding user response:
Though your question isn't clear, what about this?
foreach ($manageIds as $categoryId) {
$toDeleteIds = array_diff($allIds, $manageIds);
if (count($toDeleteIds) > 0) {
$relation->detach($toDeleteIds);
}
if (!in_array($categoryId, $allIds)) {
$relation->sync($categoryId);
}
}