/** * @param \Mageplaza\Blog\Model\Post $post * @return array */ protected function saveCategoryRelation(\Mageplaza\Blog\Model\Post $post) { $post->setIsChangedCategoryList(false); $id = $post->getId(); $categories = $post->getCategoriesIds(); if ($categories === null) { return $this; } $oldCategoryIds = $post->getCategoryIds(); $insert = array_diff_key($categories, $oldCategoryIds); $delete = array_diff_key($oldCategoryIds, $categories); $adapter = $this->getConnection(); if (!empty($delete)) { $condition = ['category_id IN(?)' => $delete, 'post_id=?' => $id]; $adapter->delete($this->postCategoryTable, $condition); } if (!empty($insert)) { $data = []; foreach ($insert as $categoryId) { $data[] = ['post_id' => (int) $id, 'category_id' => (int) $categoryId, 'position' => 1]; } $adapter->insertMultiple($this->postCategoryTable, $data); } if (!empty($insert) || !empty($delete)) { $categoryIds = array_unique(array_merge(array_keys($insert), array_keys($delete))); $this->eventManager->dispatch('mageplaza_blog_post_change_categories', ['post' => $post, 'category_ids' => $categoryIds]); } if (!empty($insert) || !empty($delete)) { $post->setIsChangedCategoryList(true); $categoryIds = array_keys($insert + $delete); $post->setAffectedCategoryIds($categoryIds); } return $this; }