【问题标题】:How to fetch the tables list in database in Laravel 5.1如何在 Laravel 5.1 中获取数据库中的表列表
【发布时间】:2016-02-02 10:00:47
【问题描述】:

我需要列出数据库中的表,我找到了这个查询

SHOW TABLES LIKE  'merTrans%'

要获取表格,但我如何使用 foreach 在 Laravel 5.1 中获取表格名称?

【问题讨论】:

    标签: php mysql laravel laravel-5


    【解决方案1】:

    对于那些喜欢使用查询生成器的人:

    DB::table('sqlite_master')
        ->whereIn('type', [ 'table', 'view' ])
        ->where('name', 'NOT LIKE', 'sqlite_%')
        ->orderBy('1')
        ->pluck('name')
        ->all()
    

    【讨论】:

      【解决方案2】:

      作为替代方案,您可以使用 information_schema.tables 来获取表名列表。

      function getTableNames($db_name, $search = ''){
              $rows = DB::select("SELECT table_name FROM information_schema.tables WHERE table_schema = '{$db_name}' AND table_name like '%{$search}%'");
      
              $table_names = [];
              foreach($rows as $row)
              {
                  $table_names[] = $row->table_name;
              }
      
              return $table_names;
      }
      
      print_r(getTableName('my_db', 'merTrans'));
      

      【讨论】:

        【解决方案3】:

        我用它来获取所有带有列的表:

        $schema = collect(DB::connection()->getDoctrineSchemaManager()->listTableNames())->map(function ($item, $key) {
          return [
            'name' => $item,
            'columns' => DB::getSchemaBuilder()->getColumnListing($item)
          ];
        });
        

        【讨论】:

          【解决方案4】:
          public function hiddenTables()
             {
                 return [
                      'migrations',
                      'password_resets',
                 ];
             }
          
          
          
          public function dbTables()
              {
                  foreach (\Illuminate\Support\Facades\DB::select('SHOW TABLES') as $tables) {
                      foreach ($tables as $table => $value)
                          $db[] = $value;
                  }
          
                  return $db;
              }
          
          
          
          public static function diffTables()
              {
                  return array_diff((new self)->dbTables(), (new self)->hiddenTables());
              }
          

          【讨论】:

          • 请考虑添加一些单词 cmets 为什么代码可以解决问题,而不仅仅是代码。
          【解决方案5】:

          "Laravel"

          的数据库中查找表列表
                  $tables_list = DB::select('SHOW TABLES');
                  
                  foreach($tables_listas $value)
                  {
                        echo $value->Tables_in_YourDatabaseName;
                  }
          

          'Tables_in_YourDatabaseName' 表示:例如,如果您的数据库名称是 "test" 那么

          echo $value->Tables_in_test;

          【讨论】:

            【解决方案6】:

            在你的 Laravel 项目中添加流动的东西:- 在控制器文件中:-

             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
            

            【讨论】:

            • 我不确定这个答案与问题有什么关系。
            【解决方案7】:

            如果您需要对所有表应用一些迁移更改。

            在 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_tablesome_2_tablesome_3_table 等。 所以基本上你现在可以使用Schema::getAllTables(),而不是DB::select('SHOW TABLES');

            【讨论】:

              【解决方案8】:

              另一种解决方案是,您不需要使用数据库名称。 'current' 将只占用第一列。

              function getTables()
              {
                  $tables = DB::select('SHOW TABLES');
              
                  $tables = array_map('current',$tables);
              
                  return $tables;
              }
              

              【讨论】:

                【解决方案9】:

                因为我没有添加评论的声誉,所以我将其发布为答案。

                Bharat 的 LIKE 案例推荐

                foreach ($tables as $table) {
                    echo array_shift(array_values($table));
                }
                

                如果您不喜欢双 foreach,但请确保您使用 var_dump $table,

                ($tables = DB::select('SHOW TABLES');
                

                查看您正在处理的确切内容。

                【讨论】:

                  【解决方案10】:
                  $tables = \DB::select("SHOW TABLES LIKE 'merTrans%'");
                  foreach ($tables as $table) {
                    echo head($table);
                  }
                  

                  【讨论】:

                  • 请编辑您的答案以包含一些解释。仅代码的答案对教育未来的 SO 读者几乎没有作用。您的答案因质量低劣而在审核队列中。
                  • 这有点 hack,因为 Laravel 的 head helper 应该适用于数组而不是对象,但它之所以有效,是因为它基本上在调用它的参数上调用 reset...跨度>
                  【解决方案11】:

                  对于 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(我猜它等同于数据库)。您可能需要稍微调整一下结果。

                  【讨论】:

                  • 我认为“显示表格”是 hack。 information_schema 是执行此操作的标准方法。
                  • 按照原问题,需要添加LIKE条件:AND table_name LIKE 'merTrans%'
                  【解决方案12】:

                  要获得一个包含所有数据库的快速数组,您可以使用以下代码:

                  // Iterate over the results of SHOW TABLES
                  // strip off all the objects and keys.
                  $tables = array_map('reset', \DB::select('SHOW TABLES'));
                  

                  对我来说,这似乎是最优雅的解决方案。

                  【讨论】:

                  • 完美的答案和最优雅的处理方式。谢谢!
                  【解决方案13】:

                  我一直在用这个:

                  $tables = DB::connection()->getDoctrineSchemaManager()->listTableNames();

                  它需要学说/dbal 作为依赖项。但是一些迁移功能已经需要 DBAL 才能工作。

                  【讨论】:

                  • 我更喜欢这个,因为我不必处理不同的数据库语法。
                  • 工作就像一个魅力。很棒的答案,这个应该被接受!
                  • 开箱即用地从数据库中获取所有表名的简短而实用的解决方案。谢谢@carlosvini
                  【解决方案14】:
                   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
                      }
                  

                  【讨论】:

                  • 这个答案适用于 mysql。如果有一些 cmets 关于为什么要这样做,我会赞成它。
                  【解决方案15】:

                  要列出数据库中的表,您可以这样做

                  $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;
                  }
                  

                  【讨论】:

                  • 没有类似的条件它工作正常。但如果我添加“LIKE 'merTrans%'”未定义属性:stdClass::$Tables_in_db_name。
                  • 双 foreach 这样的事情似乎没有必要?
                  • 注意,这个答案只适用于 MySQL。 OP 正在使用基于语法的 MySQL,但这在例如 Sqlite3 或 Postgresql 数据库中不起作用。
                  【解决方案16】:

                  在 Laravel 中你可以使用:

                  $tables = DB::select('SHOW TABLES');
                  

                  【讨论】:

                    猜你喜欢
                    • 2016-01-31
                    • 2015-11-26
                    • 1970-01-01
                    • 2015-07-12
                    • 1970-01-01
                    • 2010-10-10
                    • 1970-01-01
                    • 1970-01-01
                    • 2015-10-13
                    相关资源
                    最近更新 更多