/** * @param AuthorModel $author * @return $this */ protected function saveProductRelation(AuthorModel $author) { $author->setIsChangedProductList(false); $id = $author->getId(); $products = $author->getProductsData(); if ($products === null) { return $this; } $oldProducts = $author->getProductsPosition(); $insert = array_diff_key($products, $oldProducts); $delete = array_diff_key($oldProducts, $products); $update = array_intersect_key($products, $oldProducts); $_update = array(); foreach ($update as $key => $settings) { if (isset($oldProducts[$key]) && isset($settings['position']) && $oldProducts[$key] != $settings['position']) { $_update[$key] = $settings; } } $update = $_update; $adapter = $this->getConnection(); if (!empty($delete)) { $condition = ['product_id IN(?)' => array_keys($delete), 'author_id=?' => $id]; $adapter->delete($this->authorProductTable, $condition); } if (!empty($insert)) { $data = []; foreach ($insert as $productId => $position) { $data[] = ['author_id' => (int) $id, 'product_id' => (int) $productId, 'position' => (int) $position]; } $adapter->insertMultiple($this->authorProductTable, $data); } if (!empty($update)) { foreach ($update as $productId => $position) { $where = ['author_id = ?' => (int) $id, 'product_id = ?' => (int) $productId]; $bind = ['position' => (int) $position['position']]; $adapter->update($this->authorProductTable, $bind, $where); } } if (!empty($insert) || !empty($delete)) { $productIds = array_unique(array_merge(array_keys($insert), array_keys($delete))); $this->eventManager->dispatch('sample_news_author_change_products', ['author' => $author, 'product_ids' => $productIds]); } if (!empty($insert) || !empty($update) || !empty($delete)) { $author->setIsChangedProductList(true); $productIds = array_keys($insert + $delete + $update); $author->setAffectedProductIds($productIds); } return $this; }