Get Model Columns

@param string $model name of the table
@param string $connectionManager of the datasource

@return mixed[] $result containing key/value pairs of model columns.
760097
public static function getModelColumns(string $model = '', string $connectionManager = 'default'): array
    {
        $result = $columns = [];

        if (empty($model)) {
            return $result;
        }

        // making sure that model is in table naming conventions.
        $model = Inflector::tableize($model);

        try {
            $connection = ConnectionManager::get($connectionManager);
            $schema = $connection->getSchemaCollection();
            $table = $schema->describe($model);
            $columns = $table->columns();
        } catch (MissingDatasourceConfigException $e) {
            return $result;
        } catch (Exception $e) {
            return $result;
        }

        // A table with no columns?
        if (empty($columns)) {
            return $result;
        }

        foreach ($columns as $column) {
            $result[$column] = $column;
        }

        return $result;
    }
1269386
protected function getGuessedColumnFormatters($model, $seeding, $populateForeignKeys = false)
    {
        $this->setColumns($model);

        $formatters = [];

        $nameGuesser = new Name($this->generator);
        $columnTypeGuesser = new ColumnTypeGuesser($this->generator);

        foreach ($this->columns as $columnName => $column) {
            // Skips autoincremented primary keys.
            if ($model instanceof Model && $columnName === $model->getKeyName() && $column->getAutoincrement()) {
                continue;
            }

            // And deleted_at.
            if (
                method_exists($model, 'getDeletedAtColumn')
                && $columnName === $model->getDeletedAtColumn()
            ) {
                continue;
            }

            if (
                !$seeding && $model instanceof Model &&
                ($columnName === $model->getCreatedAtColumn() || $columnName === $model->getUpdatedAtColumn())
            ) {
                continue;
            }

            // Guesses based on the column's name, and if unable to,
            // guesses based on the column's type.
            $formatter = $nameGuesser->guessFormat($columnName, $column->getLength())
                ?: $columnTypeGuesser->guessFormat($column, $model->getTable());

            if (!$formatter) {
                continue;
            }

            if ($column->getNotnull() || !$seeding) {
                $formatters[$columnName] = $formatter;
            } else {
                $formatters[$columnName] = function () use ($formatter) {
                    return rand(0, 1) ? $formatter() : null;
                };
            }
        }

        return $populateForeignKeys ? $this->populateForeignKeys($formatters, $seeding) : $formatters;
    }
1259037
public function getForeignTableNames($tableName = null, $connectionName = null)
    {
        $foreignKeys = $this->getTableForeignKeys($tableName, $connectionName);
        $tableNames  = [];

        foreach ($foreignKeys as $foreignKey) {
            $tableNames[] = $foreignKey->getForeignTableName();
        }

        return array_unique($tableNames);
    }
206664
private function findAllRecords(Driver $driver, array $columns)
    {
        $columns = array_merge(array('id'), $columns);
        $output = array($columns);

        $this->managerFactory->setModelClass($this->modelClass);
        /** @var ModelInterface $record */
        foreach ($this->managerFactory->getManager($driver)->paginate(1, $this->maxRecords) as $record) {
            $temp = array();
            foreach ($columns as $column) {
                $temp[] = MethodInvoker::invokeGet($record, $column);
            }

            $output[] = $temp;
        }

        return $output;
    }
282352
public function getConnection($connectionName = null)
    {
        /** @var Configuration $configuration */
        $configuration = $this->get('configuration');
        $connectionName = null !== $connectionName ?: $configuration['connection_name'];
        
        return $this->getConnectionManager()->getConnection($connectionName);
    }
1367823
protected function getPropertiesFromTable($model)
    {
        $table = $model->getConnection()->getTablePrefix() . $model->getTable();
        $schema = $model->getConnection()->getDoctrineSchemaManager($table);
        $databasePlatform = $schema->getDatabasePlatform();
        $databasePlatform->registerDoctrineTypeMapping('enum', 'string');

        $platformName = $databasePlatform->getName();
        $customTypes = $this->laravel['config']->get("ide-helper.custom_db_types.{$platformName}", array());
        foreach ($customTypes as $yourTypeName => $doctrineTypeName) {
            $databasePlatform->registerDoctrineTypeMapping($yourTypeName, $doctrineTypeName);
        }

        $database = null;
        if (strpos($table, '.')) {
            list($database, $table) = explode('.', $table);
        }

        $columns = $schema->listTableColumns($table, $database);

        if ($columns) {
            foreach ($columns as $column) {
                $name = $column->getName();
                if (in_array($name, $model->getDates())) {
                    $type = '\Illuminate\Support\Carbon';
                } else {
                    $type = $column->getType()->getName();
                    switch ($type) {
                        case 'string':
                        case 'text':
                        case 'date':
                        case 'time':
                        case 'guid':
                        case 'datetimetz':
                        case 'datetime':
                            $type = 'string';
                            break;
                        case 'integer':
                        case 'bigint':
                        case 'smallint':
                            $type = 'integer';
                            break;
                        case 'boolean':
                            switch (config('database.default')) {
                                case 'sqlite':
                                case 'mysql':
                                    $type = 'integer';
                                    break;
                                default:
                                    $type = 'boolean';
                                    break;
                            }
                            break;
                        case 'decimal':
                        case 'float':
                            $type = 'float';
                            break;
                        default:
                            $type = 'mixed';
                            break;
                    }
                }

                $comment = $column->getComment();
                if (!$column->getNotnull()) {
                    $this->nullableColumns[$name] = true;
                }
                $this->setProperty($name, $type, true, true, $comment, !$column->getNotnull());
                if ($this->write_model_magic_where) {
                    $this->setMethod(
                        Str::camel("where_" . $name),
                        '\Illuminate\Database\Eloquent\Builder|\\' . get_class($model),
                        array('$value')
                    );
                }
            }
        }
    }
902043
protected function collectColumns(Model $model = null)
    {
        if (!$model) {
            return new MutableCollection([]);
        }

        $pk = $model->getKeyName();

        $fillable = array_merge(
            is_array($pk) ? $pk : [$pk],
            $model->getFillable()
        );
        $hidden = $model->getHidden();

        if ($model instanceof Translatable && method_exists($model, 'getTranslatedAttributes')) {
            $fillable = array_merge($fillable, $model->getTranslatedAttributes());
            $hidden = array_merge($hidden, $model->getTranslationModel()->getHidden());
        }

        $fillable = array_unique(array_diff($fillable, $hidden));

        /**
         * Create collection.
         */
        $elements = new MutableCollection($fillable);

        if ($this->includeDateColumns && count($dates = $model->getDates())) {
            // allow setting specific timestamp: created_at
            if (is_string($this->includeDateColumns)) {
                $dates = array_intersect($dates, [$this->includeDateColumns]);

                $elements = $elements->merge($dates);
            } else {
                // add timestamps group
                $elements->group('dates', function (Group $group) use ($dates) {
                    $group->merge($dates);

                    return $group;
                });
            }
        }

        return $elements->build(
            new GridDecorator($model)
        );
    }
1049648
public function getModelLinks(Model $model) {
        $models = Configure::read('Admin.modelLinks');

        if (isset($models[$model->qualifiedName])) {
            return $models[$model->qualifiedName];
        }

        return array();
    }
1092193
public static function getAllEntityClassNames(EntityManager $entityManager)
    {
        $classes = [];

        foreach ($entityManager->getMetadataFactory()->getAllMetadata() as $meta) {
            $classes[] = $meta->getName();
        }

        return $classes;
    }
534807
public function getModels($columns = ['*'])
    {
        $key = $this->query->getCacheKey($columns);

        $results = $this->query->get($columns);

        if ($results instanceof BaseCollection) {
            $results = $results->all();
        }

        $connection = $this->model->getConnectionName();

        $models = $this->model->hydrate($results, $connection);

        $this->tagModels($models, $key);

        return $models->all();
    }
1047517
private function readMigrated(Connection $connection): array
    {
        $builder  = $connection->createQueryBuilder();
        $migrated = [];

        if ($connection->getSchemaManager()->tablesExist([static::MIGRATIONS_TABLE]) === true) {
            $migrations = $builder
                ->select(static::MIGRATIONS_COLUMN_ID, static::MIGRATIONS_COLUMN_CLASS)
                ->from(static::MIGRATIONS_TABLE)
                ->orderBy(static::MIGRATIONS_COLUMN_ID)
                ->execute()
                ->fetchAll();
            foreach ($migrations as $migration) {
                $index            = $migration[static::MIGRATIONS_COLUMN_ID];
                $class            = $migration[static::MIGRATIONS_COLUMN_CLASS];
                $migrated[$index] = $class;
            }
        }

        return $migrated;
    }
228052
public function getModels($properties = array('*'))
    {
        // First, we will simply get the raw results from the query builders which we
        // can use to populate an array with Eloquent models. We will pass columns
        // that should be selected as well, which are typically just everything.
        $results = $this->query->get($properties);

        // Once we have the results, we can spin through them and instantiate a fresh
        // model instance for each records we retrieved from the database. We will
        // also set the proper connection name for the model after we create it.
        return $this->resultsToModels($this->model->getConnectionName(), $results, $properties);
    }
615914
public function retrieve(Model $model, $source)
    {
        return [
            'from' => parent::retrieve($model, $this->getAttributeFrom()),
            'to'   => parent::retrieve($model, $this->getAttributeTo()),
        ];
    }
478265
public function getIndexGridColumns($model, $fields)
    {
        /** @var ActiveController $controller */
        $controller = $this->controller;
        $actionColumn = new ActionColumn();
        $actionColumn->buttonOptions['class'] = 'operation-button';
        $extraColumns = [
            [
                'class'         => \yii\grid\ActionColumn::className(),
                'headerOptions' => ['class' => 'column-action'],
                'controller'    => Yii::$app->crudModelsMap[$model::className()],
                'template'      => '{update} {delete} {toggle}', // {view} removed because representing column is linked
                'buttons' => [
                    'view'   => function ($url, $model, $key) use ($controller, $actionColumn) {
                        if (!$controller->hasAccess('read', $model)) {
                            return null;
                        }

                        return $actionColumn->buttons['view']($url, $model, $key);
                    },
                    'update' => function ($url, $model, $key) use ($controller, $actionColumn) {
                        if (!$controller->hasAccess('update', $model)) {
                            return null;
                        }

                        return $actionColumn->buttons['update']($url, $model, $key);
                    },
                    'delete' => function ($url, $model, $key) use ($controller, $actionColumn) {
                        if (!$controller->hasAccess('delete', $model)) {
                            return null;
                        }

                        return $actionColumn->buttons['delete']($url, $model, $key);
                    },
                    'toggle' => function ($url, $model, $key) use ($controller, $actionColumn) {
                        /** @var \yii\db\ActiveRecord $model */
                        if ($model->getBehavior('toggable') === null || !$controller->hasAccess('delete', $model)) {
                            return null;
                        }

                        $enabled = $model->isEnabled();
                        $icon    = '<span class="glyphicon glyphicon-'.($enabled ? 'ban' : 'reply').'"></span>';
                        $options = array_merge([
                            'title'       => $enabled ? Yii::t('app', 'Disable') : Yii::t('app', 'Enable'),
                            'aria-label'  => $enabled ? Yii::t('app', 'Disable') : Yii::t('app', 'Enable'),
                            'data-pjax'   => '0',
                        ], $enabled ? [
                            'data-confirm' => Yii::t('app', 'Are you sure you want to disable this item?'),
                        ] : [], $actionColumn->buttonOptions);
                        return \yii\helpers\Html::a($icon, $url, $options);
                    },
                ],
            ],
        ];
        if ($this->useSerialColumn) {
            $extraColumns[] = [
                'class'         => \yii\grid\SerialColumn::className(),
                'headerOptions' => ['class' => 'column-serial'],
            ];
        }
        if ($this->useCheckboxColumn) {
            //$classParts = explode('\\', $this->modelClass);
            $extraColumns[] = [
                'class'         => \yii\grid\CheckboxColumn::className(),
                'headerOptions' => ['class' => 'column-checkbox'],
                'multiple'      => true,
                //'name'          => end($classParts).'[]',
            ];
        }

        return array_merge($extraColumns, static::getGridColumns($model, $fields));
    }
135457
public function getModelColumns()
    {
        $model = $this->getForeignModelInstance();
        $columns = [];
        if ($this->isModel($model)) {
            // At this point we know a model class exists
            // Try to get the database column listing from the database directly
            $tableName = $model->getTable();
            $columns = DB::getSchemaBuilder()->getColumnListing($tableName);
        }

        if (count($columns) == 0) {
            // At this poing we know the column have not yet been identified
            // which also mean that the model does not exists or the table
            // does not existing in the database.
            // Try to find the columns from the resource-file if one found.
            $columns = $this->getFieldNamesFromResource();
        }

        return $columns;
    }
1243767
public function getEntityManager()
    {

        // check if we have a valid datasource node
        if ($this->getDatasourceNode() == null) {
            return;
        }

        // prepare the path to the entities
        $absolutePaths = array();
        if ($relativePaths = $this->getStepNode()->getParam(AbstractDatabaseStep::PARAM_PATH_TO_ENTITIES)) {
            foreach (explode(PATH_SEPARATOR, $relativePaths) as $relativePath) {
                $absolutePaths[] = $this->getWebappPath() . DIRECTORY_SEPARATOR . $relativePath;
            }
        }

        // load the database connection parameters
        $connectionParameters = $this->getConnectionParameters();

        // initialize and load the entity manager and the schema tool
        $metadataConfiguration = Setup::createAnnotationMetadataConfiguration($absolutePaths, true, null, null, false);
        return EntityManager::create($connectionParameters, $metadataConfiguration);
    }
702424
protected function getQueryResults(array $models) {
        if (empty($this->relations)) {
            return static::getRelationQuery($models)->all();
        }
        $data = static::getRelationQuery($models)->appendSelect($this->getRelationFields())->all();
        if (empty($data)) {
            return $data;
        }
        foreach ($this->relations as $relation) {
            if (empty($relation->getKey())) {
                return $relation->getResults($data);
            }
            $data = $relation->getResults($data);
        }
        return $data;
    }