protected function saveCategoryRelation(AuthorModel $author) { $author->setIsChangedCategoryList(false); $id = $author->getId(); $categories = $author->getCategoriesIds(); if ($categories === null) { return $this; } $oldCategoryIds = $author->getCategoryIds(); $insert = array_diff_key($categories, $oldCategoryIds); $delete = array_diff_key($oldCategoryIds, $categories); $adapter = $this->getConnection(); if (!empty($delete)) { $condition = array('category_id IN(?)' => $delete, 'author_id=?' => $id); $adapter->delete($this->authorCategoryTable, $condition); } if (!empty($insert)) { $data = array(); foreach ($insert as $categoryId) { $data[] = array('author_id' => (int) $id, 'category_id' => (int) $categoryId, 'position' => 1); } $adapter->insertMultiple($this->authorCategoryTable, $data); } if (!empty($insert) || !empty($delete)) { $categoryIds = array_unique(array_merge(array_keys($insert), array_keys($delete))); $this->eventManager->dispatch('sample_news_author_change_categories', array('author' => $author, 'category_ids' => $categoryIds)); } if (!empty($insert) || !empty($delete)) { $author->setIsChangedCategoryList(true); $categoryIds = array_keys($insert + $delete); $author->setAffectedCategoryIds($categoryIds); } return $this; }