/** * @param AuthorModel $author * @return $this */ protected function saveStoreRelation(AuthorModel $author) { $oldStores = $this->lookupStoreIds($author->getId()); $newStores = (array) $author->getStores(); if (empty($newStores)) { $newStores = (array) $author->getStoreId(); } $table = $this->getTable('sample_news_author_store'); $insert = array_diff($newStores, $oldStores); $delete = array_diff($oldStores, $newStores); if ($delete) { $where = ['author_id = ?' => (int) $author->getId(), 'store_id IN (?)' => $delete]; $this->getConnection()->delete($table, $where); } if ($insert) { $data = []; foreach ($insert as $storeId) { $data[] = ['author_id' => (int) $author->getId(), 'store_id' => (int) $storeId]; } $this->getConnection()->insertMultiple($table, $data); } return $this; }