Jeffrey
Jeffrey

Reputation: 4146

Yii check if db column exists before creating it

I'm looking to check if a database column exists within a table before I create the column. I know this can be done easily using pure sql, but I would like to try to do it the Yii way using the db schema functions.

This if statement below doesn't work cause there isn't a getColumn function, so using db->schema what else can be used to check whether the column ($model->VARNAME) exists?

if(!Yii::app()->db->schema->getColumn($form->TABLE_NAME, $model->VARNAME))
{
    if($model->save())
    {
        Yii::app()->db->schema->addColumn($form->TABLE_NAME, $model->VARNAME, $column_t);
        $this->redirect(array('view','field'=>$model->FIELD_ID));
    }
}
else
{
    $model->addError('VARNAME','Column "'.$model->VARNAME.'" already exists. Please pick a new column name.');
}

Upvotes: 7

Views: 12982

Answers (4)

Akmal
Akmal

Reputation: 553

Code in Yii2:

$columnData = $this
    ->getDb()
    ->getSchema()
    ->getTableSchema('table_name')
    ->getColumn('column_name');

if ($columnData) {
    // Columns exists, do something!
}

Returns null if column doesn't exist, else returns object with infomation about existing column.

Upvotes: 9

Prabhash Choudhary
Prabhash Choudhary

Reputation: 151

As per Yii 2.0, it should do the trick:

$table = Yii::$app->db->schema->getTableSchema('mytable');
if (!isset($table->columns['somecolumn'])) {
    // do something
}

Upvotes: 15

Michael Härtl
Michael Härtl

Reputation: 8597

// Fetch the table schema
$table = Yii::app()->db->schema->getTable('mytable');
if(!isset($table->columns['somecolumn'])) {
    // Column doesn't exist
}

Upvotes: 12

Samuel Liew
Samuel Liew

Reputation: 79042

You will want to use $model->hasAttribute():

if( $model->hasAttribute('VARNAME') )

e.g.:

if( $model->hasAttribute('title') )

if( $model->hasAttribute($varname) )

Upvotes: 1

Related Questions