php 有什么方法可以检测 Laravel 中是否存在数据库表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15935990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:13:03  来源:igfitidea点击:

Is there any way to detect if a database table exists with Laravel

phplaravel

提问by Ehsan Zargar Ershadi

I want to be able to create a table using

我希望能够使用

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

But before that I would like to check if the table already exists, perhaps something like

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

Schema::exists('mytable');

However, the above function does not exist. What else can I use?

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

回答by Phill Sparks

If you are using Laravel 4 or 5 then there is the hasTable()method, you can find it in the L4 source codeor the L5 docs:

如果您使用的是 Laravel 4 或 5,则有该hasTable()方法,您可以在 L4 源代码L5 文档中找到它:

Schema::hasTable('mytable');

回答by B. R. N. Rajoriya

To create a new table there is only one check by Laravel Schema function hasTable.

要创建一个新表,Laravel Schema 函数只需进行一项检查hasTable

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

But if you want to drop any table before checking its existence then Schema have a function called dropIfExists.

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

Schema::dropIfExists('table_name');

It will drop the table if table will exist.

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

回答by pankaj kumar

if you are using different connection then you have to go with my answer.

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

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

here on hasTable()function you can pass more than 1 table name.

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

回答by mckendricks

No built in function for this in L3. You can do a raw query:

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 …
}

回答by Bimal Poudel

Rather, depend on information schema query instead of checking for some data in the tables with COUNT().

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

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

Change your 'table_name'value.

改变你的'table_name'价值。

If you get one row output, it means the table exists.

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