【问题标题】:Is there any way to detect if a database table exists with Laravel有什么方法可以用 Laravel 检测数据库表是否存在
【发布时间】:2013-04-02 21:25:57
【问题描述】:

我希望能够使用

Schema::create('mytable',function($table)
{
    $table->increments('id');
    $table->string('title');
});

但在此之前,我想检查表是否已经存在,可能类似于

Schema::exists('mytable');

但是,上述功能不存在。我还能用什么?

【问题讨论】:

  • 你能告诉你在哪个文件中添加了这段代码吗?

标签: php laravel


【解决方案1】:

如果你使用的是 Laravel 4 或 5,那么有 hasTable() 方法,你可以找到它 in the L4 source codeL5 docs

Schema::hasTable('mytable');

【讨论】:

  • call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'hasTable',我使用了DB::hasTable('test'),因为找不到Schema类。
  • 试试 DB::connection('xxxx')->getSchemaBuilder()->hasTable('xxx')
  • 我试试这个,它正在工作......DB::getSchemaBuilder()->hasTable('table_name_without_prefix')
  • Schema::connection("bio_db")->hasTable('deviceLogs_11_2019')
  • @ShakeelAhmed 表和视图信息分别存储在模式中。您可以按照stackoverflow.com/a/57959796/1269513 的建议自行查询架构
【解决方案2】:

要创建一个新表,只需通过 Laravel Schema 函数hasTable 进行一次检查。

if (!Schema::hasTable('table_name')) {
    // Code to create table
}

但是如果你想在检查它是否存在之前删除任何表,那么 Schema 有一个名为 dropIfExists 的函数。

Schema::dropIfExists('table_name');

如果表存在,它将删除该表。

【讨论】:

    【解决方案3】:

    如果您使用不同的连接,那么您必须接受我的回答。

    Schema::connection("bio_db")->hasTable('deviceLogs_11_2019')
    

    hasTable() 函数上,您可以传递多个表名。

    【讨论】:

      【解决方案4】:

      正如 Phill Sparks 回答的那样,您可以使用以下方法检查表是否存在:

      Schema::hasTable('mytable')
      

      请注意,您的应用有时会使用不同的连接。在这种情况下,您应该使用:

      Schema::connection('myConnection')->hasTable('mytable')
      

      (不要忘记在代码开头使用use Schema;)。

      【讨论】:

        【解决方案5】:

        在 L3 中没有内置函数。您可以进行原始查询:

        $table = "foo";
        $check = DB::only('SELECT COUNT(*) as `exists`
            FROM information_schema.tables
            WHERE table_name IN (?)
            AND table_schema = database()',$table);
        if(!$check) // No table found, safe to create it.
        {
            // Schema::create …
        }
        

        【讨论】:

        • 谢谢!.. 我正在使用 Laravel 3。
        • 这不是跨数据库类型的完全交叉兼容。例如,它不适用于 Sqlite 或 Oracle。
        【解决方案6】:

        而是依赖于信息模式查询,而不是使用COUNT()检查表中的某些数据。

        SELECT table_schema 
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
              AND table_name = 'table_name';
        

        更改您的 'table_name' 值。

        如果得到一行输出,则表示该表存在。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-17
          • 1970-01-01
          • 2010-11-04
          • 2018-01-31
          • 1970-01-01
          • 2013-01-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多