Bal*_*ran 28 php mysql laravel-5.1
我需要列出tables
中database
,我找到了查询
SHOW TABLES LIKE 'merTrans%'
Run Code Online (Sandbox Code Playgroud)
得到表格,但我怎么能用它foreach
来获取表名Laravel 5.1
?
Bha*_*eda 49
要列出数据库中的表,您可以执行此操作
$tables = DB::select('SHOW TABLES');
foreach($tables as $table)
{
echo $table->Tables_in_db_name;
}
Run Code Online (Sandbox Code Playgroud)
您必须将db_name更改为数据库的名称.
编辑:像个案一样
foreach ($tables as $table) {
foreach ($table as $key => $value)
echo $value;
}
Run Code Online (Sandbox Code Playgroud)
car*_*ini 35
我一直在用这个:
$tables = DB::connection()->getDoctrineSchemaManager()->listTableNames();
它要求学说/ dbal作为依赖.但是一些迁移功能已经需要DBAL才能工作.
小智 20
要获得包含所有数据库的快速数组,您可以使用以下代码:
// Iterate over the results of SHOW TABLES
// strip off all the objects and keys.
$tables = array_map('reset', \DB::select('SHOW TABLES'));
Run Code Online (Sandbox Code Playgroud)
对我来说,这似乎是最优雅的解决方案.
对于Postgres用户:
SHOW TABLES
不支持所以你必须做一些更多的hackey.
$tables = DB::select("SELECT table_schema,table_name, table_catalog FROM information_schema.tables WHERE table_catalog = 'YOUR TABLE CATALOG HERE' AND table_type = 'BASE TABLE' AND table_schema = 'public' ORDER BY table_name;")
Run Code Online (Sandbox Code Playgroud)
确保填写table_catalog(我猜这与数据库相同).您可能需要稍微调整一下您的结果.
小智 6
如果您需要对所有表应用一些迁移更改。
在 Laravel 6 中Schema::getAllTables()
成为公共方法,所以你可以这样做:
$tables = array_filter(
Schema::getAllTables(),
static function ($table) {
return preg_match('/some_(\d+)_table/', $table->{'Tables_in_' . env('DB_DATABASE')});
}
);
foreach ($tables as $table ) {
Schema::table(
$table->{'Tables_in_' . env('DB_DATABASE')},
static function (Blueprint $table) {
$table->removeColumn('request_id');
}
);
}
Run Code Online (Sandbox Code Playgroud)
当您需要对具有以下命名结构的表执行某些操作(在上面的例子中 - 删除列)时,这是相关的:some_1_table
、some_2_table
、some_3_table
等。所以基本上DB::select('SHOW TABLES');
您现在可以使用Schema::getAllTables()
.
小智 5
$tables = \DB::select("SHOW TABLES LIKE 'merTrans%'");
foreach ($tables as $table) {
echo head($table);
}
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是,您不需要使用数据库名称。“当前”将仅占据第一列。
function getTables()
{
$tables = DB::select('SHOW TABLES');
$tables = array_map('current',$tables);
return $tables;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
38336 次 |
最近记录: |