/** * @param \Mageplaza\Blog\Model\Post $post * @return $this */ protected function saveTopicRelation(\Mageplaza\Blog\Model\Post $post) { $post->setIsChangedTopicList(false); $id = $post->getId(); $topics = $post->getTopicsData(); if ($topics === null) { return $this; } $oldTopics = $post->getTopicsPosition(); $insert = array_diff_key($topics, $oldTopics); $delete = array_diff_key($oldTopics, $topics); $update = array_intersect_key($topics, $oldTopics); $_update = []; foreach ($update as $key => $settings) { if (isset($oldTopics[$key]) && $oldTopics[$key] != $settings['position']) { $_update[$key] = $settings; } } $update = $_update; $adapter = $this->getConnection(); if (!empty($delete)) { $condition = ['topic_id IN(?)' => array_keys($delete), 'post_id=?' => $id]; $adapter->delete($this->postTopicTable, $condition); } if (!empty($insert)) { $data = []; foreach ($insert as $topicId => $position) { $data[] = ['post_id' => (int) $id, 'topic_id' => (int) $topicId, 'position' => (int) $position['position']]; } $adapter->insertMultiple($this->postTopicTable, $data); } if (!empty($update)) { foreach ($update as $topicId => $position) { $where = ['post_id = ?' => (int) $id, 'topic_id = ?' => (int) $topicId]; $bind = ['position' => (int) $position['position']]; $adapter->update($this->postTopicTable, $bind, $where); } } if (!empty($insert) || !empty($delete)) { $topicIds = array_unique(array_merge(array_keys($insert), array_keys($delete))); $this->eventManager->dispatch('mageplaza_blog_post_change_topics', ['post' => $post, 'topic_ids' => $topicIds]); } if (!empty($insert) || !empty($update) || !empty($delete)) { $post->setIsChangedTopicList(true); $topicIds = array_keys($insert + $delete + $update); $post->setAffectedTopicIds($topicIds); } return $this; }