Exemple #1
0
 /**
  * Move category to another parent node
  *
  * @param \Mirasvit\Blog\Model\Category $category
  * @param \Mirasvit\Blog\Model\Category $newParent
  * @param null|int                      $afterCategoryId
  * @return $this
  */
 public function changeParent(\Mirasvit\Blog\Model\Category $category, \Mirasvit\Blog\Model\Category $newParent, $afterCategoryId = null)
 {
     $childrenCount = $this->getChildrenCount($category->getId()) + 1;
     $table = $this->getEntityTable();
     $connection = $this->getConnection();
     $levelFiled = $connection->quoteIdentifier('level');
     $pathField = $connection->quoteIdentifier('path');
     /**
      * Decrease children count for all old category parent categories
      */
     $connection->update($table, ['children_count' => new \Zend_Db_Expr('children_count - ' . $childrenCount)], ['entity_id IN(?)' => $category->getParentIds()]);
     /**
      * Increase children count for new category parents
      */
     $connection->update($table, ['children_count' => new \Zend_Db_Expr('children_count + ' . $childrenCount)], ['entity_id IN(?)' => $newParent->getPathIds()]);
     $position = $this->processPositions($category, $newParent, $afterCategoryId);
     $newPath = sprintf('%s/%s', $newParent->getPath(), $category->getId());
     $newLevel = $newParent->getLevel() + 1;
     $levelDisposition = $newLevel - $category->getLevel();
     /**
      * Update children nodes path
      */
     $connection->update($table, ['path' => new \Zend_Db_Expr('REPLACE(' . $pathField . ',' . $connection->quote($category->getPath() . '/') . ', ' . $connection->quote($newPath . '/') . ')'), 'level' => new \Zend_Db_Expr($levelFiled . ' + ' . $levelDisposition)], [$pathField . ' LIKE ?' => $category->getPath() . '/%']);
     /**
      * Update moved category data
      */
     $data = ['path' => $newPath, 'level' => $newLevel, 'position' => $position, 'parent_id' => $newParent->getId()];
     $connection->update($table, $data, ['entity_id = ?' => $category->getId()]);
     // Update category object to new data
     $category->addData($data);
     $category->unsetData('path_ids');
     return $this;
 }