我需要在tables
中列出database
,我找到了对的查询
SHOW TABLES LIKE 'merTrans%'
获取表,但是如何使用foreach
获取Laravel 5.1
中的表名?
$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; }
function getTables()
{
$tables = DB::select('SHOW TABLES');
$tables = array_map('current',$tables);
return $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
等。因此,基本上可以用DB::select('SHOW TABLES');
代替Schema::getAllTables()
。
$tables = DB::connection()->getDoctrineSchemaManager()->listTableNames();
它需要教义/ dbal作为依赖项。但是某些迁移功能已经需要DBAL才能起作用。
// 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(我想它等同于数据库)。您可能需要稍微调整一下结果。
$tables = DB::select('SHOW TABLES');
$tables = \DB::select("SHOW TABLES LIKE 'merTrans%'");
foreach ($tables as $table) {
echo head($table);
}
对巴拉特喜欢的情况的建议
foreach ($tables as $table) {
echo array_shift(array_values($table));
}
如果您不喜欢使用双重foreach,但请确保您使用var_dump $ table,
($tables = DB::select('SHOW TABLES');
确切地了解您正在处理的内容。
protected function getNamesTablesDB(){
$database = Config::get('database.connections.mysql.database');
$tables = DB::select('SHOW TABLES');
$combine = "Tables_in_".$database;
$collection = new \Illuminate\Database\Eloquent\Collection;
foreach($tables as $table){
$collection->put($table->$combine, $table->$combine);
}
return $collection; //or compact('collection'); //for combo select
}
public function debate_list(){
$records = DB::table('table_name')->get();
return view('page_link')->with('records',$records);
}
在page_link.blade.php中添加流动的:-
@foreach($records as $class) <tr> <td>{{$class->id}}</td> <td> {{$class->name}} </td> <td> {{$class->image_url}} </td> <td> {{ $class->created_at }} </td> <td> <a class="btn btn-primary btn-sm " href="{{route('image_status_list')}}"> VIEW</a> </td> </tr> @endforeach