【问题标题】:Laravel foreign key uuidLaravel 外键 uuid
【发布时间】:2021-05-06 14:09:51
【问题描述】:

我对 Laravel 的 uuid 外键有一些问题。 我创建了如下表:

Schema::create('product_attributes', function (Blueprint $table) {
            $table->uuid('id');
            $table->string('label');
            $table->integer('default_order')->nullable();
            $table->timestamps();
        });

        Schema::create('product_attributes_value', function (Blueprint $table) {
            $table->uuid('id');
            $table->unsignedBigInteger('attribute_id');
            $table->string('value');
            $table->integer('default_order')->nullable();

            $table->foreign('attribute_id')->references('id')->on('product_attributes');
            $table->timestamps();
        });

它总是给予

SQLSTATE[HY000]:一般错误:1005 无法创建表 ecommerce.product_attributes_value (errno: 150 "外键 约束格式不正确”)(SQL:alter table product_attributes_value 添加约束 product_attributes_value_attribute_id_foreign外键 (attribute_id) 引用product_attributes (id))

我看不出有问题,可以吗?

【问题讨论】:

  • $table->unsignedBigInteger('attribute_id');$table->uuid('attribute_id'); 两个数据类型应该相同

标签: php mysql laravel


【解决方案1】:

您将整数列映射到 uuid 列,product_attributes_value 表中的 attribute_id 列的类型应与 中的 id 列相同>product_attributes

改变:

$table->unsignedBigInteger('attribute_id');

到:

$table->uuid('attribute_id')->nullable(false);

【讨论】:

    【解决方案2】:

    改变

    $table->foreign('attribute_id')
    

    $table->unsignedBigInteger('attribute_id')
    

    【讨论】:

    • $table->uuid('id'); 具有无符号属性的主键,在创建外键时两个属性相同,否则返回 error
    • 请通过编辑将所有解释添加到您的答案中 - 请记住,其他人应该能够从中学习
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2021-11-12
    • 2015-10-27
    • 2021-05-24
    • 2020-12-13
    • 1970-01-01
    • 2022-12-03
    相关资源
    最近更新 更多