【问题标题】:Access laravel migration and return the return the Blueprint table object访问 laravel 迁移并返回返回蓝图表对象
【发布时间】:2019-04-21 04:03:36
【问题描述】:

我想知道是否有一种方法可以访问迁移文件中的蓝图并将其返回到外部文件中。例如,我有以下 USERS 迁移:

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

所以我想知道我是否可以“访问”这个对象以在外部文件中使用它。想象一下,我有一个文件 get_data_from_migration.blade.php,我可以执行以下操作:

use Illuminate\Database\Migrations\Migration;

$table = Migration('migrationName');
var_dump($table);

所以它会在屏幕上打印用户表蓝图。 我知道这不是正确的语法,但我只是用它来说明这个想法。

无论如何,我需要在屏幕上打印如下内容:

表格中的列是:

  • 身份证
  • 姓名
  • 电子邮件
  • email_verified_at
  • 密码

谢谢

【问题讨论】:

    标签: php laravel database-migration


    【解决方案1】:

    你可以试试这样的:

    use Illuminate\Support\Facades\Schema;
    
    // for your User model
    $table = $user->getTable();
    $columns = Schema::getColumnListing($table);
    

    或者,如果您没有 User 的实例,您可以尝试:

    use Illuminate\Support\Facades\Schema;
    
    $table = with(new User)->getTable();
    $columns = Schema::getColumnListing($table);
    

    或者,如果您只想要一个模型,您可以硬编码表名。

    use Illuminate\Support\Facades\Schema;
    
    $columns = Schema::getColumnListing('users');
    

    【讨论】:

    • 第一个和第三个示例找不到架构。第二个只返回一个字符串“users”
    • 是的,你需要导入Schema门面类。我已经更新了答案以包含它。
    • 对不起,我试图“使用”它,但可能做错了什么。现在可以了,谢谢。现在有机会拿到类型吗?像(id-increments),(name-string)
    • 安装doctrine/dbal包时,可以使用DB::connection()->getDoctrineSchemaManager()->listTables()等方法获取数据库结构信息。
    猜你喜欢
    • 2015-04-18
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2020-07-04
    • 2016-05-24
    相关资源
    最近更新 更多