Exemplo n.º 1
0
 /**
  * Updates an existing Table model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     if ($model->load(Yii::$app->request->post())) {
         if ($model->status == Table::STATUS_ACTIVE) {
             if (($fields = Field::findAll(['table_id' => $model->id])) !== null) {
                 try {
                     Table::createTable($model->id);
                     $modelName = Table::generateModelFromTable($model->system_name);
                     Table::generateCrudFromModel($modelName);
                     Yii::$app->getSession()->setFlash('success', 'Таблица создана, файлы сгенерированы.');
                 } catch (Exception $e) {
                     Yii::$app->getSession()->setFlash('error', $e->getMessage());
                     return $this->redirect(['update', 'id' => $model->id]);
                 }
             } else {
                 Yii::$app->getSession()->setFlash('error', 'Чтобы создать таблицу нужно добавить столбцы.');
                 return $this->redirect(['update', 'id' => $model->id]);
             }
         }
         if ($model->save()) {
             return $this->redirect(['view', 'id' => $model->id]);
         }
     }
     return $this->render('update', ['model' => $model]);
 }
Exemplo n.º 2
0
 /**
  * @param $id
  * @throws \yii\db\Exception
  */
 public static function createTable($id)
 {
     if (($table = Table::findOne((int) $id)) !== null) {
         if (($fields = Field::findAll(['table_id' => $table->id])) !== null) {
             $query = "";
             foreach ($fields as $item) {
                 $type = $item['fieldType']->type;
                 $query .= "`{$item->system_name}` {$type}" . ($item->length ? "({$item->length})" : "") . " NOT NULL" . ($item->default ? " DEFAULT '{$item->default}'" : "") . " COMMENT '{$item->name}',";
             }
             $query = "CREATE TABLE `{$table->system_name}` (\n                    `id` INT(11) NOT NULL AUTO_INCREMENT,\n                    {$query}\n                    PRIMARY KEY (`id`)\n                )\n                " . ($table->description ? "COMMENT='{$table->description}'" : "") . "\n                COLLATE='utf8_unicode_ci'\n                ENGINE=InnoDB\n                ;";
             Yii::$app->db->createCommand($query)->execute();
         }
     }
 }