Laravel获取所有的数据库表及结构的方法

吾爱主题 阅读:141 2021-08-30 16:25:00 评论:0

遇到一个需求,需要修改数据库中所有包含email的字段的表,要把里面的长度改为128位。Laravel获取所有的表,然后循环判断表里面有没有email这个字段。

代码如下:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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 ); }
?
1 2 Schema::getColumnListing( 'user' ); Schema::hasColumn( $table , $column_name )

这里记一笔,比知道有没有更好的方法一步获取到当前连接的数据库里面的所有的表,我是用原生的sql语句show tables查出所有表,然后取出Tables_in_new_bcc_web这一列,然后才得到所有的表名,然后再去循环。

找到一个更棒的方式:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 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获取所有的数据库表及结构的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/zhezhebie/article/details/78589812

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容