我需要列出数据库中的表,我找到了这个查询
SHOW TABLES LIKE 'merTrans%'
我想获取表格,但如何使用foreach
在Laravel 5.1中获取表格名称?
$tables = DB::connection()->getDoctrineSchemaManager()->listTableNames();
要列出数据库中的表,您可以执行以下操作
$tables = DB::select('SHOW TABLES');
foreach($tables as $table)
{
echo $table->Tables_in_db_name;
}
您需要将db_name更改为您数据库的名称。
编辑:对于类似情况
foreach ($tables as $table) {
foreach ($table as $key => $value)
echo $value;
}
要快速获取包含所有数据库的数组,您可以使用以下代码段:
// Iterate over the results of SHOW TABLES
// strip off all the objects and keys.
$tables = array_map('reset', \DB::select('SHOW TABLES'));
对我来说,这似乎是最优雅的解决方案。
对于Postgres用户:
SHOW TABLES
不受支持,因此您需要采取一些更加巧妙的方法。
$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;")
请确保您填写了table_catalog(我猜它等同于数据库)。您可能需要稍微调整一下您的结果。
AND table_name LIKE 'merTrans%'
。 - Masa Sakano$tables = DB::select('SHOW TABLES');
如果你需要对所有表应用某些迁移更改。
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');
}
);
}
当你需要做一些与表格相关的事情时(在上述情况中,是删除一列),以下命名结构的表格就会变得重要:some_1_table
、some_2_table
、some_3_table
等等。
所以,基本上你现在可以使用 Schema::getAllTables()
代替 DB::select('SHOW TABLES');
。
$tables = \DB::select("SHOW TABLES LIKE 'merTrans%'");
foreach ($tables as $table) {
echo head($table);
}
head
helper 应该用于数组而不是对象,但它能够工作是因为它基本上在传递给它的参数上调用了 reset
... - guessimtoolatefunction getTables()
{
$tables = DB::select('SHOW TABLES');
$tables = array_map('current',$tables);
return $tables;
}
我使用以下代码获取带列的所有表格:
$schema = collect(DB::connection()->getDoctrineSchemaManager()->listTableNames())->map(function ($item, $key) {
return [
'name' => $item,
'columns' => DB::getSchemaBuilder()->getColumnListing($item)
];
});
因为我还没有足够的声望来添加评论,所以我将其发布为答案。
对于Bharat的LIKE CASES建议。
foreach ($tables as $table) {
echo array_shift(array_values($table));
}
($tables = DB::select('SHOW TABLES');
查看您所处理的内容。
composer req doctrine/dbal
。(如果尚未安装) - Erlang Parasu