I need to check if a table exists in a database. I currently develop using Yii2.
My case is a bit different from this question because the table to be checked is not (and can not be) a model.
I have tried (new \yii\db\Query())->select('*')->from($mysticTable)->exists());
The above throws a yii\db\Exception
because, according to question linked above, the yii\db\Query()
class tries to ->queryScalar()
when asked if ->exists()
. Invariably, this method checks if the result-set exists.
How do I check if a table exists?
For Yii2 you can use:
$tableSchema = Yii::$app->db->schema->getTableSchema('tableName');
If the table does not exist, it will return null
, so you can check returned value for being null
:
if ($tableSchema === null) {
// Table does not exist
}
You can find this method in official docs here.