Example #1
0
 /**
  *
  * @param Table $table
  * @return bool
  */
 public function createRoot($table)
 {
     if (!$table->isLoaded()) {
         throw new \Exception('Node must be loaded.');
         return false;
     }
     if (!$table->isTree()) {
         throw new \Exception('Model must be a tree.');
         return false;
     }
     if ($table->isInTree()) {
         throw new \Exception('Node already in a tree.');
         return false;
     }
     $site_id = \hat\common\SystemConfig::getSiteId();
     $id = $table->get('id');
     $table_name = $table->getTableName();
     $behavior_name = 'nestedset';
     $lft_key = $table->getBehavior()->getFieldName($behavior_name, 'lft');
     $rgt_key = $table->getBehavior()->getFieldName($behavior_name, 'rgt');
     $level_key = $table->getBehavior()->getFieldName($behavior_name, 'level');
     $root_id_key = $table->getBehavior()->getFieldName($behavior_name, 'root_id');
     $this->reset();
     $sql = "SELECT MAX({$root_id_key}) FROM {$table_name} WHERE {$root_id_key} > 0";
     if ($table->getBehavior()->isIt('multitenant')) {
         $tenant_identifier = $table->getBehavior()->getFieldName('multitenant', 'identifier');
         $sql .= " AND {$tenant_identifier} = {$site_id} ";
     }
     $r = $this->queryStmt($sql);
     if ($r !== false) {
         $r = $this->getResultsDbRow();
     } else {
         throw new \Exception("Error creating root:" . $this->getLastPdoErrorMessage());
         return false;
     }
     $root_id = 0;
     if (isset($r[0]) && isset($r[0]['max'])) {
         $root_id = $r[0]['max'];
     }
     $root_id++;
     // increment for next root_id
     $this->reset();
     $sql = "UPDATE {$table_name} SET {$root_id_key} = {$root_id}, {$lft_key} = 1, {$rgt_key} = 2, {$level_key} = 0 WHERE id = {$id} ";
     if ($table->getBehavior()->isIt('multitenant')) {
         $tenant_identifier = $table->getBehavior()->getFieldName('multitenant', 'identifier');
         $sql .= " AND {$tenant_identifier} = {$site_id} ";
     }
     $r = $this->queryStmt($sql);
     if ($r !== false) {
         $r = $this->getResultsDbRow();
     } else {
         throw new \Exception("Error creating root:" . $this->getLastPdoErrorMessage());
         return false;
     }
     //\hat\dbg::alert($r, true);
     return true;
 }