使用 PersistCollection 添加或删除新旧类别的优雅方式

问题描述 投票:0回答:1

我所做的事情非常丑陋。它有效,但是在 symfony 中是否有任何“优雅”的方式来做到这一点?我自己在文档中找不到有用的东西。我所做的是:

/**
         * @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);

有没有办法比较

requestedCategories
中的 id,以便在
oldCategoryIds
中丢失并将它们从数据库中删除。 DB可以自己处理。

php symfony doctrine-orm doctrine filtering
1个回答
0
投票

不要认为有一种开箱即用的“优雅”方法。但另一种方法可能是:

/** @var Collection<Category> $removedCategories */
$removedCategories = $currentCategories->filter(
    function (Category $category) use ($requestCategories) {
        return false === in_array($category->getId(), $requestCategories, true);
    }
);
© www.soinside.com 2019 - 2024. All rights reserved.