Create the Model

@throws \Exception
@return void
552079
private function createMigration(): void
    {
        try {

            $oNow    = Factory::factory('DateTime');
            $aFields = [
                'INDEX'      => $this->oInput->getArgument('index'),
                'DATE_START' => $oNow->format('Y-m-d'),
            ];

            if (is_null($aFields['INDEX'])) {

                //  Get the most recent migration and increment it by 1
                $sPattern    = \Nails\Common\Console\Command\Database\Migrate::VALID_MIGRATION_PATTERN;
                $aMigrations = [];
                foreach (new \DirectoryIterator(static::MIGRATION_PATH) as $oFileInfo) {

                    if ($oFileInfo->isDot()) {
                        continue;
                    }

                    //  In the correct format?
                    if (preg_match($sPattern, $oFileInfo->getFilename(), $aMatches)) {
                        $aMigrations[] = (int) $aMatches[1];
                    }
                }

                sort($aMigrations);

                if (!empty($aMigrations)) {
                    $aFields['INDEX'] = end($aMigrations) + 1;
                } else {
                    $aFields['INDEX'] = 0;
                }

            } elseif (!is_numeric($aFields['INDEX'])) {
                throw new NailsException('Specified migration index is not a numeric value.');
            } else {
                $aFields['INDEX'] = (int) $aFields['INDEX'];
            }

            $this->oOutput->write('Creating migration <comment>' . $aFields['INDEX'] . '</comment>... ');

            //  Check for existing controller
            $sPath = static::MIGRATION_PATH . $aFields['INDEX'] . '.php';
            if (file_exists($sPath)) {
                throw new MigrationExistsException(
                    'Migration "' . $aFields['INDEX'] . '" exists already at path "' . $sPath . '"'
                );
            }

            //  If we're making the first migration, get a dump of all the non-Nails tables
            $aFields['QUERIES'] = '';
            if ($aFields['INDEX'] === 0 && stringToBoolean($this->oInput->getOption('sql-on-zero'))) {

                $oDb      = Factory::service('Database');
                $aResult  = $oDb->query('SHOW TABLES')->result();
                $aCreates = [];

                foreach ($aResult as $oResult) {
                    $aResult = (array) $oResult;
                    $sTable  = reset($aResult);
                    if (!preg_match('/^' . NAILS_DB_PREFIX . '/', $sTable) || $sTable == NAILS_DB_PREFIX . 'user_meta_app') {
                        $aResult    = (array) $oDb->query('SHOW CREATE TABLE ' . $sTable)->row();
                        $aCreates[] = 'DROP TABLE IF EXISTS ' . $aResult['Table'] . ';' . "\n" . $aResult['Create Table'];
                    }
                }

                foreach ($aCreates as $sCreate) {

                    $aCreate = explode("\n", $sCreate);
                    $iCount  = count($aCreate);
                    array_walk(
                        $aCreate,
                        function (&$sLine, $iIndex) use ($iCount) {
                            $sLine = trim($sLine);
                            if ($iIndex > 1 && $iIndex < ($iCount - 1)) {
                                $sLine = $this->tabs(4) . $sLine;
                            } else {
                                $sLine = $this->tabs(3) . $sLine;
                            }
                        }
                    );

                    $aFields['QUERIES'] .= $this->tabs(2) . '$this->query(\'' . "\n";
                    $aFields['QUERIES'] .= str_replace("'", "\'", implode("\n", $aCreate)) . "\n";
                    $aFields['QUERIES'] .= $this->tabs(2) . '\');' . "\n";
                }

                $aFields['QUERIES'] = trim($aFields['QUERIES']);
                $aFields['QUERIES'] = str_replace(NAILS_DB_PREFIX, '{{NAILS_DB_PREFIX}}', $aFields['QUERIES']);
                $aFields['QUERIES'] = str_replace(APP_DB_PREFIX, '{{APP_DB_PREFIX}}', $aFields['QUERIES']);
                $aFields['QUERIES'] = preg_replace('/AUTO_INCREMENT=\d+ /', '', $aFields['QUERIES']);

            } else {
                $aFields['QUERIES'] = '$this->query(\'\');';
            }

            $this->createFile($sPath, $this->getResource('template/migration.php', $aFields));
            $aCreated[] = $sPath;
            $this->oOutput->writeln('<info>done!</info>');

        } catch (\Exception $e) {
            $this->oOutput->writeln('<error>failed!</error>');
            //  Clean up created models
            if (!empty($aCreated)) {
                $this->oOutput->writeln('<error>Cleaning up - removing newly created migration</error>');
                foreach ($aCreated as $sPath) {
                    @unlink($sPath);
                }
            }
            throw new NailsException($e->getMessage());
        }
    }
759405
protected function createModel()
    {
        if (!$this->_model instanceof \MUtil_Model_SelectModel) {
            $trackId = $this->trackId;

            $db     = $this->db;
            $select = $db->select()->distinct()->from('gems__rounds', ['gro_round_description', 'gro_round_description'])->where('gro_id_track = ?', $trackId);
            $rounds = $this->db->fetchPairs($select);

            $fields = [
                'gems__surveys.gsu_survey_name',
                'round_order' => new \Zend_Db_Expr('min(gro_id_order)')
            ];
            foreach ($rounds as $round) {
                $fields[$round] = new \Zend_Db_Expr('max(case when (gro_round_description = ' . $db->quote($round) . ' AND gro_condition IS NULL) then "X" when gro_round_description = ' . $db->quote($round) . ' then "C" else NULL end)');
            }
            $fields['filler'] = new \Zend_Db_Expr('COALESCE(gems__track_fields.gtf_field_name, gems__groups.ggp_name)');

            $sql = $this->db->select()->from('gems__rounds', [])
                    ->join('gems__surveys', 'gro_id_survey = gsu_id_survey', [])
                    ->joinLeft('gems__track_fields', 'gro_id_relationfield = gtf_id_field AND gtf_field_type = "relation"', array())
                    ->joinLeft('gems__groups', 'gsu_id_primary_group =  ggp_id_group', array())
                    ->where('gro_active = 1')   //Only active rounds
                    ->where('gro_id_track = ?', $trackId)
                    ->group(['gro_id_survey', 'filler'])
                    ->columns($fields);

            $model = new \MUtil_Model_SelectModel($sql, 'track-plan');
            //$model->setKeys(array('gsu_survey_name'));
            $model->resetOrder();
            $model->set('filler', 'label', $this->_('Filler'));
            $model->set('gsu_survey_name', 'label', $this->_('Survey'));            
            foreach ($rounds as $round) {
                $model->set($round, 'label', $round);
            }
            $this->_model = $model;
        }

        return $this->_model;
    }
1157344
public function actionCreate()
    {
        /* @var $model ActiveRecord */
        $model = $this->createModel();
        $model->load(Yii::$app->request->post(), '');
        $model->save();

        return $model;
    }
384108
public function createInstance()
    {
        $classname = $this->getPlatformClassname();

        if (!class_exists($classname)) {
            throw new \Exception(
                sprintf('Unable to locate class %s', $classname)
            );
        }

        return new $classname();
    }
381907
public function createInstance()
    {
        $classname = $this->getEngineClassname();

        if (!class_exists($classname)) {
            throw new \Exception(
                sprintf('Unable to locate class %s', $classname)
            );
        }

        return new $classname();
    }
1129008
public function createInstance()
    {
        $classname = $this->getProjectClassname();

        if (!class_exists($classname)) {
            throw new \Exception(
                sprintf('Unable to locate class %s', $classname)
            );
        }

        return new $classname();
    }
785700
public function create()
	{
		$class = __NAMESPACE__ . '\\Scaffolding\\' . ucfirst($this->type);

		if (class_exists($class))
		{
			$obj = new $class($this->output, $this->arguments);
		}
		else
		{
			if (empty($this->type))
			{
				$this->output->error('Error: Sorry, scaffolding can\'t create nothing/everything. Try telling it what you want to create.');
			}
			else
			{
				$this->output->error('Error: Sorry, scaffolding doesn\'t know how to create a ' . $this->type);
			}
		}

		// Get author name and email - we'll go ahaed and retrieve for all create calls
		$user_name  = Config::get('user_name');
		$user_email = Config::get('user_email');

		if (!$user_name || !$user_email)
		{
			$this->output
			     ->addSpacer()
			     ->addLine('You can specify your name and email via:')
			     ->addLine(
					'muse configuration set --user_name="John Doe"',
					array(
						'indentation' => '2',
						'color'       => 'blue'
					)
				)
				->addLine(
					'muse configuration set --user_email=john.doe@gmail.com',
					array(
						'indentation' => '2',
						'color'       => 'blue'
					)
				)
				->addSpacer()
				->error("Error: failed to retrieve author name and/or email.");
		}

		$obj->addReplacement('author_name', $user_name)
			->addReplacement('author_email', $user_email);

		// Call the construct method
		$obj->construct();
	}
806724
protected function createModel()
    {
        $model = parent::createModel();

        $model->addColumn('CONCAT(gr2t_completed, \'' . $this->_(' of ') . '\', gr2t_count)', 'progress');
        $model->set('progress', 'label', $this->_('Progress'), 'tdClass', 'rightAlign', 'thClass', 'rightAlign');

        return $model;
    }
320643
protected static function boot()
    {
        parent::boot();

        // Boot event for creating this model.
        // Set default values if specified.
        // Validate dirty attributes before commiting to save.
        static::creating(function ($model) {
            $model->setDefaultValuesForAttributes();
            if (!$model->savingValidation()) {
                $validator = $model->getValidator();
                $issues = $validator->errors()->all();

                $message = sprintf(
                    "Validation failed on creating %s.\n%s",
                    $model->getTable(),
                    implode("\n", $issues)
                );

                throw new Exceptions\ValidationException($message, 0, null, $validator);
            }
        });

        // Boot event once model has been created.
        // Add missing attributes using the schema.
        static::created(function ($model) {
            $model->addMissingAttributes();
        });

        // Boot event for updating this model.
        // Validate dirty attributes before commiting to save.
        static::updating(function ($model) {
            if (!$model->savingValidation()) {
                $validator = $model->getValidator();
                $issues = $validator->errors()->all();

                $message = sprintf(
                    "Validation failed on saving %s (%s).\n%s",
                    $model->getTable(),
                    $model->getKey(),
                    implode("\n", $issues)
                );

                throw new Exceptions\ValidationException($message, 0, null, $validator);
            }
        });
    }
621498
public function create(): Model
	{
		$model_class = $this->getModelClass();
		$instance = new $model_class;
		$this->fill($instance);

		return $instance;
	}
345867
protected function createTables()
    {
        if (empty( self::$tables )) {
            throw new \Exception('Cannot create tables, as no configuration file given, or the ::$tables is not overridden.');
        }
        $client = $this->dynamoDb->getClient();

        foreach (self::$tables as $tableData) {
            $tableName = $tableData['TableName'];

            if ( ! $this->tableExists($tableName)) {
                $this->comment(sprintf('Creating table %s', $tableName));

                $client->createTable($tableData);

                $client->waitUntil('TableExists', array(
                    'TableName' => $tableName,
                ));

                $this->info(sprintf('Table "%s" created.', $tableName));
            } else {
                $this->warn(sprintf('Table "%s" already exists.', $tableName));
            }
        }
    }
835763
protected function create()
    {
        $fields = [];
        $keys = [];

        foreach ($this->getCurrentTable()->getFields() as $name => $field) {
            $fields[] = implode(' ', [
                '`' . $field->getName() . '`',
                $field->getType() . '(' . $field->getLength() . ')',
                ($field->isUnsigned()) ? 'UNSIGNED' : '',
                ($field->isNullable() ? '' : ('NOT NULL')),
                (!$field->isIncrement() && !$field->isUnique() && !$field->isPrimary() ? 'DEFAULT "' . $field->getDefault() . '"' : '') ,
                ($field->isIncrement()) ? 'AUTO_INCREMENT' : '',
                'COMMENT "' . $field->getComment() . '"'
            ]);

            if (null !== $field->getKey()) {
                if ($field->isPrimary()) {
                    $keys[] = 'PRIMARY KEY (`' . $field->getName() . '`)';
                } else if ($field->isUnique()) {
                    $keys[] = 'UNIQUE KEY `unique_' . $field->getName() . '` (`' . $field->getName() . '`)';
                } else if ($field->isIndex()) {
                    $keys[] = 'KEY `index_' . $field->getName() . '` (`' . $field->getName() . '`)';
                }
            }

            $this->setCacheField($field);
        }

        $this->saveCache();

        $schema = $this->isForce() ? ('DROP TABLE IF EXISTS `' . $this->getCurrentTable()->getFullTableName() . '`;' . PHP_EOL . PHP_EOL) : '';
        $schema .= 'CREATE TABLE `' . $this->getCurrentTable()->getFullTableName() . '` (';
        $schema .= PHP_EOL . implode(',' . PHP_EOL, $fields) . (empty($keys) ? PHP_EOL : (',' . PHP_EOL . implode(',' . PHP_EOL, $keys) . PHP_EOL));
        $schema .= ') ENGINE ' . $this->getCurrentTable()->getEngine() . ' CHARSET ' . $this->getCurrentTable()->getCharset() . ' COMMENT "' . $this->getCurrentTable()->getComment() . '";';

        return $schema;
    }
481879
public function create()
    {
        $this->loadModel('Content.ContentTypes');
        $types = $this->ContentTypes->find()
            ->select(['id', 'slug', 'name', 'description'])
            ->all();

        $this->title(__d('content', 'Create New Content'));
        $this->set('types', $types);
        $this->Breadcrumb
            ->push('/admin/content/manage')
            ->push(__d('content', 'Create new content'), '');
    }
726637
public function newAction()
    {
        $model = $this->loadModel();
        if (!$model->isObjectNew()) {
            $this->_forward('noroute');
            return;
        }

        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();
            try {
                $model->isObjectNew(true);
                foreach ($this->preprocessPostData($postData) as $key => $value) {
                    $model->setDataUsingMethod($key, $value);
                }
                $model->save();
                $this->_redirectUrl($this->getHelper()->getGridUrl());
                $this->_getSession()->addSuccess('Saved Successfully');
                return;
            } catch (Exception $e) {
                $message = $e->getMessage();
                if ($e instanceof Zend_Db_Statement_Exception && $e->getChainedException() instanceof PDOException) {
                    /** @var PDOException $e */
                    $e = $e->getChainedException();
                    if (isset($e->errorInfo[0]) && $e->errorInfo[0] == 23000 && isset($e->errorInfo[1]) && $e->errorInfo[1] == 1062) {
                        $message = $this->getHelper()->__(
                            "Record already exists for %s '%s'",
                            $model->getIdFieldName(),
                            $model->getId()
                        );
                    }
                }
                Mage::logException($e);
                $this->_getSession()->addError($message);
            }
        }

        $this->loadLayout();
        $this->renderLayout();
    }
237668
protected function createFactory()
    {
        $factory = Str::studly(class_basename($this->argument('name')));

        $this->call('make:factory', [
            'name' => "{$factory}Factory",
            '--model' => $this->argument('name'),
        ]);
    }
16858
protected function createModel()
    {
        if (! $this->model instanceof EpisodeOfCareModel) {
            $this->model = $this->loader->getModels()->createEpisodeOfCareModel();

            $this->model->applyBrowseSettings();
        }

        if ($this->calSearchFilter instanceof AppointmentFilterInterface) {
            $this->model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr'), 'order', 3);

            \Gems_Model_RespondentModel::addNameToModel($this->model, $this->_('Name'));

            $this->model->set('name', 'order', 6);
        }

        // \MUtil_Model::$verbose = true;
        return $this->model;
    }
1296622
public function create() {
        $migration = $this->getMessages();
        if (!$migration) {
            $this->db()->insert($this->table, array('migration' => get_class($this), 'state' => false));
        } else {
            throw new \Exception('Migration ' .  get_class($this) . ' already created');
        }
    }