Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.');
}
like image 889
Jeffrey Avatar asked Aug 30 '13 19:08

Jeffrey


2 Answers

// Fetch the table schema
$table = Yii::app()->db->schema->getTable('mytable');
if(!isset($table->columns['somecolumn'])) {
    // Column doesn't exist
}
like image 126
Michael Härtl Avatar answered Oct 05 '22 23:10

Michael Härtl


As per Yii 2.0, it should do the trick:

$table = Yii::$app->db->schema->getTableSchema('mytable');
if (!isset($table->columns['somecolumn'])) {
    // do something
}
like image 31
Prabhash Choudhary Avatar answered Oct 05 '22 22:10

Prabhash Choudhary