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.');
}
// 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With