简体   繁体   English

Yii 在创建 db 列之前检查它是否存在

[英]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.我知道这可以使用纯 sql 轻松完成,但我想尝试使用 db 模式函数以 Yii 方式完成。

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 语句不起作用,因为没有 getColumn 函数,所以使用 db->schema 还有什么可以用来检查列 ($model->VARNAME) 是否存在?

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.');
}

As per Yii 2.0, it should do the trick:根据 Yii 2.0,它应该可以解决问题:

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

Code in Yii2: 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.如果列不存在,则返回 null,否则返回包含有关现有列的信息的对象。

You will want to use $model->hasAttribute() :您将要使用$model->hasAttribute()

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

eg:例如:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM