/** * @param \Mageplaza\Blog\Model\Category $category * @return $this */ protected function savePostRelation(\Mageplaza\Blog\Model\Category $category) { $category->setIsChangedPostList(false); $id = $category->getId(); $posts = $category->getPostsData(); if ($posts === null) { return $this; } $oldPosts = $category->getPostsPosition(); $insert = array_diff_key($posts, $oldPosts); $delete = array_diff_key($oldPosts, $posts); $update = array_intersect_key($posts, $oldPosts); $_update = []; foreach ($update as $key => $position) { if (isset($oldPosts[$key]) && $oldPosts[$key] != $position) { $_update[$key] = $position; } } $update = $_update; $adapter = $this->getConnection(); if (!empty($delete)) { $condition = ['post_id IN(?)' => array_keys($delete), 'category_id=?' => $id]; $adapter->delete($this->categoryPostTable, $condition); } if (!empty($insert)) { $data = []; foreach ($insert as $postId => $position) { $data[] = ['category_id' => (int) $id, 'post_id' => (int) $postId, 'position' => (int) $position]; } $adapter->insertMultiple($this->categoryPostTable, $data); } if (!empty($update)) { foreach ($update as $postId => $position) { $where = ['category_id = ?' => (int) $id, 'post_id = ?' => (int) $postId]; $bind = ['position' => (int) $position]; $adapter->update($this->categoryPostTable, $bind, $where); } } if (!empty($insert) || !empty($delete)) { $postIds = array_unique(array_merge(array_keys($insert), array_keys($delete))); $this->eventManager->dispatch('mageplaza_blog_category_change_posts', ['category' => $category, 'post_ids' => $postIds]); } if (!empty($insert) || !empty($update) || !empty($delete)) { $category->setIsChangedPostList(true); $postIds = array_keys($insert + $delete + $update); $category->setAffectedPostIds($postIds); } return $this; }