Example #1
0
 /**
  * @param ArticleModel $article
  * @return $this
  */
 protected function saveProductRelation(ArticleModel $article)
 {
     $article->setIsChangedProductList(false);
     $id = $article->getId();
     $products = $article->getProductsData();
     if ($products === null) {
         return $this;
     }
     $oldProducts = $article->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]) && $oldProducts[$key] != $settings['position']) {
             $_update[$key] = $settings;
         }
     }
     $update = $_update;
     $adapter = $this->getConnection();
     if (!empty($delete)) {
         $condition = ['product_id IN(?)' => array_keys($delete), 'article_id=?' => $id];
         $adapter->delete($this->articleProductTable, $condition);
     }
     if (!empty($insert)) {
         $data = [];
         foreach ($insert as $productId => $position) {
             $data[] = ['article_id' => (int) $id, 'product_id' => (int) $productId, 'position' => (int) $position];
         }
         $adapter->insertMultiple($this->articleProductTable, $data);
     }
     if (!empty($update)) {
         foreach ($update as $productId => $position) {
             $where = ['article_id = ?' => (int) $id, 'product_id = ?' => (int) $productId];
             $bind = ['position' => (int) $position['position']];
             $adapter->update($this->articleProductTable, $bind, $where);
         }
     }
     if (!empty($insert) || !empty($delete)) {
         $productIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
         $this->eventManager->dispatch('gemtoo_blog_article_change_products', ['article' => $article, 'product_ids' => $productIds]);
     }
     if (!empty($insert) || !empty($update) || !empty($delete)) {
         $article->setIsChangedProductList(true);
         $productIds = array_keys($insert + $delete + $update);
         $article->setAffectedProductIds($productIds);
     }
     return $this;
 }