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

sbdsn5lh  于 2023-10-18  发布在  PostgreSQL
关注(0)|答案(3)|浏览(134)

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

  1. public function up()
  2. {
  3. Schema::create('restaurant_tables', function(Blueprint $table){
  4. $table->increments('_id');
  5. $table->string('tableNo', 100);
  6. $table->json('spatialLocation');
  7. $table->enum('tableStatus' , array('Occupied', 'Reserved', 'Vacant', 'For Cleaning'))->default('Vacant');
  8. $table->integer('numberOfCustomers');
  9. $table->integer('seatLimit');
  10. $table->string('tableDimension', 100);
  11. $table->enum('tableType', ['4x4','16x4','8x4']);
  12. $table->bigInteger('chairID');
  13. });
  14. Schema::table('restaurant_tables', function(Blueprint $table){
  15. $table->foreign('chairID')->references('_id')->on('restaurant_chairs');
  16. });
  17. }

z8dt9xmd

z8dt9xmd1#

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

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

umuewwlo2#

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

第一个默认

2izufjch

2izufjch3#

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

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

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

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

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

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Models\Types;
  4. use Doctrine\DBAL\Types\StringType;
  5. class TableTypeEnumDbType extends StringType
  6. {
  7. public function getName(): string
  8. {
  9. return 'tableTypeEnum';
  10. }
  11. }

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

  1. /*
  2. |--------------------------------------------------------------------------
  3. | Doctrine DBAL settings.
  4. |--------------------------------------------------------------------------
  5. */
  6. 'dbal' => [
  7. 'types' => [
  8. 'tableTypeEnum' => \App\Models\Types\AdStatusType::class,
  9. ],
  10. ],
展开查看全部

相关问题