postgresql 我如何创建laravel迁移与枚举类型列?

sbdsn5lh  于 12个月前  发布在  PostgreSQL
关注(0)|答案(3)|浏览(110)

我试图在laravel迁移中创建枚举列。在执行查询时,它确实在表中创建了列,但是在postgresql中检查创建的枚举类型,它显示没有。有人经历过吗?
我用的是laravel 5.4,php 7和vagrant
迁移代码

public function up()
    {
        Schema::create('restaurant_tables', function(Blueprint $table){
            $table->increments('_id');
            $table->string('tableNo', 100);
            $table->json('spatialLocation');
            $table->enum('tableStatus' , array('Occupied', 'Reserved', 'Vacant', 'For Cleaning'))->default('Vacant');
            $table->integer('numberOfCustomers');
            $table->integer('seatLimit');
            $table->string('tableDimension', 100);
            $table->enum('tableType', ['4x4','16x4','8x4']);
            $table->bigInteger('chairID');
        });

        Schema::table('restaurant_tables', function(Blueprint $table){
            $table->foreign('chairID')->references('_id')->on('restaurant_chairs');
        });
    }

z8dt9xmd

z8dt9xmd1#

您可以简单地执行以下操作:

$table -> enum('tableStatus',['VACANT','OCCUPIED','RESERVED','FOR CLEANING'])->default('VACANT');
umuewwlo

umuewwlo2#

$table->enum('tableStatus',['Vacant', 'Reserved', 'Occupied', 'For Cleaning']);

第一个默认

2izufjch

2izufjch3#

以下是解释:https://hbgl.dev/add-columns-with-custom-types-in-laravel-migrations/
希望这将为那些像我一样遇到这个问题的人节省保存一些时间。
简而言之:

Grammar::macro('typeTableTypeEnum', function () {
    return 'tableTypeEnum';
});
 
DB::unprepared("CREATE TYPE tableTypeEnum AS ENUM ('4x4','16x4','8x4');");
 
Schema::create('restaurant_tables', function (Blueprint $table) {
    ...
    $table->addColumn('tableType', 'tableTypeEnum');
    ...
});

替代版本(用于现有表格更新):

DB::unprepared("CREATE TYPE \"tableTypeEnum\" AS ENUM ('4x4','16x4','8x4');");
DB::unprepared('ALTER TABLE "restaurant_tables" add column "tableType" "tableTypeEnum" NOT NULL');

扩展Doctrine DBAL的其他步骤(例如,重命名时需要):
1.创建类TableTypeEnumDbType

<?php

declare(strict_types=1);

namespace App\Models\Types;

use Doctrine\DBAL\Types\StringType;

class TableTypeEnumDbType extends StringType
{
    public function getName(): string
    {
        return 'tableTypeEnum';
    }
}

1.把它添加到config/database.php

/*
|--------------------------------------------------------------------------
| Doctrine DBAL settings.
|--------------------------------------------------------------------------
*/
'dbal' => [
    'types' => [
        'tableTypeEnum' => \App\Models\Types\AdStatusType::class,
    ],
],

相关问题