yii\db\mysql\Schema::findColumns PHP Method

findColumns() protected method

Collects the metadata of table columns.
protected findColumns ( yii\db\TableSchema $table ) : boolean
$table yii\db\TableSchema the table metadata
return boolean whether the table exists in the database
    protected function findColumns($table)
    {
        $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteTableName($table->fullName);
        try {
            $columns = $this->db->createCommand($sql)->queryAll();
        } catch (\Exception $e) {
            $previous = $e->getPrevious();
            if ($previous instanceof \PDOException && strpos($previous->getMessage(), 'SQLSTATE[42S02') !== false) {
                // table does not exist
                // https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
                return false;
            }
            throw $e;
        }
        foreach ($columns as $info) {
            if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_LOWER) {
                $info = array_change_key_case($info, CASE_LOWER);
            }
            $column = $this->loadColumnSchema($info);
            $table->columns[$column->name] = $column;
            if ($column->isPrimaryKey) {
                $table->primaryKey[] = $column->name;
                if ($column->autoIncrement) {
                    $table->sequenceName = '';
                }
            }
        }
        return true;
    }

Usage Example

Example #1
0
 /**
  * @inheritdoc
  */
 protected function findColumns($table)
 {
     if (parent::findColumns($table)) {
         if (!count($table->primaryKey)) {
             foreach ($table->columns as $column) {
                 if (preg_match('~^pk_~', $column->name)) {
                     $table->primaryKey[] = $column->name;
                 }
             }
             if (!count($table->primaryKey)) {
                 foreach ($table->columns as $column) {
                     $table->primaryKey[] = $column->name;
                     break;
                 }
             }
         }
         return true;
     }
     return false;
 }