'Elegant way to add or remove new and old categories with PersistCollection

What I did is pretty ugly. It works but is there any "Elegant" way of doing this in symfony ? Couldn't find something useful in the documentation by myself. What I did is:

/**
         * @var PersistentCollection $currentCategories
         */
        $currentCategories = $product->getCategories();
        /**
         * @var array $requestCategories
         */
        $requestCategories = $request->getCategories();

        foreach ($currentCategories as $category) {
            $oldCategoryIds[] = $category->getId();
        }

        $forRemove = array_diff($oldCategoryIds, $requestCategories);
        $forSave = array_diff($requestCategories, $oldCategoryIds);

Is there a way to compare the ids in the requestedCategories for such that miss in the oldCategoryIds and remove them from the DB. The DB can handle by myself.



Solution 1:[1]

Don't think there's an out-of-the-box "elegant" approach to this. But an alternative approach could be:

/** @var Collection<Category> $removedCategories */
$removedCategories = $currentCategories->filter(
    function (Category $category) use ($requestCategories) {
        return false === in_array($category->getId(), $requestCategories, true);
    }
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeroen van der Laan