【问题标题】:Laravel Database migrations Schema builder custom column typeLaravel 数据库迁移 Schema builder 自定义列类型
【发布时间】:2018-01-28 21:52:23
【问题描述】:

我正在尝试使用 Laravel 创建迁移,但我需要自定义列类型,因为我想要的列类型不包含在架构生成器中,即“POLYGON”。所以我想知道,除了那些已经在 Schema builder 中的之外,我如何创建我的自定义列类型。

我想要的在 SQL 语句中是这样的:

alter table xxx add polygon POLYGON not null

是否可以自己做,或者我不得不使用像this 这样的库?

我知道我可以这样做:

DB::statement('ALTER TABLE country ADD COLUMN polygon POLYGON');

但它导致我表不存在的错误。

【问题讨论】:

    标签: laravel laravel-schema-builder


    【解决方案1】:

    没有内置方法可以做到这一点,但您可以用最少的代码获得良好的结果。

    <?php
    
    use Illuminate\Database\Schema\Grammars\Grammar;
    
    // Put this in a service provider's register function.
    Grammar::macro('typePolygon', function (Fluent $column) {
        return 'POLYGON';
    });
     
    // This belongs in a migration.
    Schema::create('my_table', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->addColumn('polygon', 'my_foo');
    });
    

    关键是在 Grammar 类中添加一个名为 typePolygon 的函数,因为这个函数决定了特定 DBMS 使用的实际类型。我们通过在语法中添加一个宏来实现这一点。

    我写了一篇关于如何将此解决方案扩展到任何自定义类型的博文:https://hbgl.dev/add-columns-with-custom-types-in-laravel-migrations/

    【讨论】:

    • 语法对我不起作用:方法 Illuminate\Database\Schema\Grammars\PostgresGrammar::typeStatus 不存在。
    • @hGBI 在一个全新的 laravel 8 项目中我刚刚创建了一个迁移到“my_table”并复制并粘贴了您的代码:gist.github.com/gilbertoalbino/d577db94057a98c653a72e0d638db31e
    • @GilbertoAlbino 我无法重现我这边的错误。我还创建了一个新的 Laravel 项目,创建了一个新的迁移,粘贴了您的代码,运行了迁移,它运行良好。如果您找到问题的原因,请告诉我。
    【解决方案2】:

    我假设您需要数据库中的空间字段...我会考虑通过 Packagist.org 并搜索 laravel-geo (或等效) - 它支持空间列类型 inc Polygon。然后,您可以为您的自定义字段使用标准 Laravel 迁移文件 - 例如

    $table->polygon('column_name');
    

    在迁移文件中的 UP 函数中...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 2019-01-26
      • 2012-10-17
      • 2016-01-02
      • 2018-04-04
      • 2017-01-26
      • 1970-01-01
      相关资源
      最近更新 更多