1. 程式人生 > 實用技巧 >Laravel獲取所有的資料庫表及結構的方法

Laravel獲取所有的資料庫表及結構的方法

遇到一個需求,需要修改資料庫中所有包含email的欄位的表,要把裡面的長度改為128位。Laravel獲取所有的表,然後迴圈判斷表裡面有沒有email這個欄位。

程式碼如下:

use Illuminate\Support\Facades\Schema;
use DB;

public function getDatabaseColumns() {
 $tables = DB::select('show tables');
 $tables = array_column($tables, 'Tables_in_new_bcc_web');
 $columns = ['email', 'user_name', 'nick_name', 'first_name', 'last_name'];
 // dd(Schema::getConnection());
 foreach ($tables as $key => $value) {
  foreach ($columns as $k => $v) {
   if (Schema::hasColumn($value, $v)) {
    $table[] = $value;
   };
  }
  // $columns[] = Schema::getColumnListing('users');
 }
 $table = array_unique($table);
 dd($table);
}
Schema::getColumnListing('user');
Schema::hasColumn($table, $column_name)

這裡記一筆,比知道有沒有更好的方法一步獲取到當前連線的資料庫裡面的所有的表,我是用原生的sql語句show tables查出所有表,然後取出Tables_in_new_bcc_web這一列,然後才得到所有的表名,然後再去迴圈。

找到一個更棒的方式:

public function getDatabaseColumns() {
 $tables = array_map('reset', \DB::select('SHOW TABLES'));
 $columns = ['email', 'user_name', 'nick_name', 'first_name', 'last_name'];
 foreach ($tables as $key => $value) {
  foreach ($columns as $k => $v) {
   if (Schema::hasColumn($value, $v)) {
    $table[] = $value;
   };
  }
 }
 $table = array_unique($table);
 dd($table);
}

以上這篇Laravel獲取所有的資料庫表及結構的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援碼農教程。