在丢弃之前检查表是否存在?

时间:2010-07-10 22:05:33

标签: doctrine doctrine-1.2

我正在尝试在删除之前检查表的存在。我已经阅读了Doctrine_Table的API文档,我似乎找不到这样的东西。有什么我想念的吗?

我的代码看起来像是:

$table = new Doctrine_Table('model_name', $conn);

$export = new Doctrine_Export();

$export->dropTable($table->getTableName());

当表不存在时我得到的错误是:

致命错误:未捕获的异常'Doctrine_Connection_Mysql_Exception',消息'SQLSTATE [42S02]:未找到基表或视图:1051未知表

提前致谢,

凯西

4 个答案:

答案 0 :(得分:20)

Doctrine2方法是:

$schemaManager = $this->getDoctrine()->getConnection()->getSchemaManager();
if ($schemaManager->tablesExist(array('users')) == true) {
      // table exists! ...
}

答案 1 :(得分:4)

如果您只想在表存在时返回true / false,这就是我所做的:

public function checkTable($table)
{
    $conn = Doctrine_Manager::connection();
    try { $conn->execute("DESC $table"); }
    catch (Exception $e) { return false; }
    return true;
}

答案 2 :(得分:2)

以下是我最终使用的内容......欢迎任何改进建议:

public static function isInstalled()
{
    $installed = true;

    $q = Doctrine_Query::create($conn);
    $q->select('t.id');
    $q->from('Table t'); //the table to check

    try {
        $q->execute();
    } catch (Doctrine_Connection_Exception $e) {
        // we only want to silence 'no such table' errors
        if ($e->getPortableCode() !== Doctrine_Core::ERR_NOSUCHTABLE) {
            throw new Doctrine_Export_Exception($e->getMessage());
        }

        $installed = false;
    }

    return $installed;
}

答案 3 :(得分:0)

我没有测试过可移植性,但在本机SQL中你可以这样做:

DROP TABLE IF EXISTS ...

您也可以使用Doctrine运行本机SQL查询。