Table Not Existing Table With Cdbcommand

Does anybody know how to set option to create table with


only if it not exists? I’m trying to create table with this method and if table already exists I have an exception. How can I construct query like


with this method? Ofcourse I can use raw query with

createCommand("CREATE TABLE IF NOT EXIST...")

but it’s not cool:) Does Yii has much more pretty approach?

I think your existing approach of creating the raw query will turn out to be cleanest. You could do something like this though:

if ($connection->schema->getTable('table_name') === null)


    // Table does not exist, so create here


There’s an inherent race condition and I’m not quite sure how it would all fit together with database permissions and such.

If you’re doing multiple creations, you could get the table names first and check if each table exists in the array to cut down on your separate queries.

$tableNames = $connection->schema->getTableNames();

if (!isset($tableNames['table_name']))


    // Create