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.');
}
You will want to use $model->hasAttribute()
:
if( $model->hasAttribute('VARNAME') )
e.g.:
if( $model->hasAttribute('title') )
if( $model->hasAttribute($varname) )
// Fetch the table schema
$table = Yii::app()->db->schema->getTable('mytable');
if(!isset($table->columns['somecolumn'])) {
// Column doesn't exist
}
As per Yii 2.0, it should do the trick:
$table = Yii::$app->db->schema->getTableSchema('mytable');
if (!isset($table->columns['somecolumn'])) {
// do something
}
Code in Yii2: $this->getDb()->getSchema()->getTableSchema('table_name')->getColumn('column_name');
Returns null if column doesn't exist, else returns object with infomation about existing column.