Yii check if db column exists before creating it
10,520
Solution 1
As per Yii 2.0, it should do the trick:
$table = Yii::$app->db->schema->getTableSchema('mytable');
if (!isset($table->columns['somecolumn'])) {
// do something
}
Solution 2
// Fetch the table schema
$table = Yii::app()->db->schema->getTable('mytable');
if(!isset($table->columns['somecolumn'])) {
// Column doesn't exist
}
Solution 3
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.
Solution 4
You will want to use $model->hasAttribute()
:
if( $model->hasAttribute('VARNAME') )
e.g.:
if( $model->hasAttribute('title') )
if( $model->hasAttribute($varname) )
Related videos on Youtube
Author by
Jeffrey
Updated on September 15, 2022Comments
-
Jeffrey 3 months
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.'); }
-
Jeffrey over 9 yearsI was needing a way to check if a table column exists (from a dynamic active record model) that is different from the current "$model" model. Anyway I ended up solving this using the db->createCommand() column functions rather than the db->schema. Thanks anyways :)
-
d.raev almost 5 yearsI was going to down-vote this ... it works .. it make sense if you look a bit at it .. and it is much more simple and easy to remember. It even works if your model is out of sync ... and hos noting "defined" for this column.
-
d.raev almost 5 yearssuggested use for php7 : if( (new MyClass)->hasAttribute('my_column') ){