如何使用带有 Idiorm 的 PDO 检查表是否存在

How to check if a tables exists using PDO with Idiorm

/**
 * Check if a table exists in the current database.
 *
 * @param PDO $pdo PDO instance connected to a database.
 * @param string $table Table to search for.
 * @return bool TRUE if table exists, FALSE if no table found.
 */
function tableExists($pdo, $table) {

    // Try a select statement against the table
    // Run it in try/catch in case PDO is in ERRMODE_EXCEPTION.
    try {
        $result = $pdo->query("SELECT 1 FROM $table LIMIT 1");
    } catch (Exception $e) {
        // We got an exception == table not found
        return FALSE;
    }

    // Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
    return $result !== FALSE;
}
  1. 如何用Idiorm PDO配置这个功能?
  2. 可以用-

    try {
        $page = ORM::for_table($table)->where('slug', $slug )->find_one();  
    } (catch $e) {
        // 404 with an error that table does not exists.
    }
    

而不是 "tableExists" 函数?

如果我对你的问题的理解正确,你想检查 table 是否存在于 MySQL 数据库中。

问。 1

需要注意的是,这两个查询并不相同。你有:

$page = ORM::for_table($table)->where('slug', $slug )->find_one();

但是你的第二个查询应该是:

$page = ORM::for_table($table)->select_expr(1)->find_one();

有关信息,请参阅 result columns documentation

问。 2

是的,Idiorm 在底层使用 PDO,因此您将获得相同的 PDO 异常 - 这是您真正可以尝试的东西,看看它是如何工作的:

try {
    $page = ORM::for_table($table)->where('slug', $slug )->find_one();  
} (catch $e) {
    var_dump($e);
}