【问题标题】:SQLSTATE[HY000]: General error: 1005 Can't create table `ic`.`livros`(errno: 150 "Foreign key constraint is incorrectly formed") id`))SQLSTATE [HY000]:一般错误:1005 无法创建表 `ic`.`livros`(errno: 150 "外键约束格式不正确") id`))
【发布时间】:2021-09-23 16:47:58
【问题描述】:

我想从表“users”中用de外键“users_id”创建de表“livros”,但我无法迁移。

表格:

public function up()
    {
        Schema::create('livros', function (Blueprint $table) {
            $table->id();
 
            $table->integer('users_id');
            $table->foreign('users_id')->references('id')->on('users');
            /*Auth::user()->id;*/

            $table->text('namel');
            $table->string('autor');
            $table->string('editora');
            $table->string('categoria');
            $table->string('classificação');
            $table->text('descricao');
            $table->string('image')->nullable();
            $table->timestamp('created_at')->nullable();
            $table->timestamp('updated_at')->nullable();


        });
    } 

【问题讨论】:

  • 把这个改成$table->unsignedBigInteger('users_id');
  • livros 上的 users_id 和 users 上的 id 的列定义必须匹配。默认情况下,在 Laravel 8 中,主键的列定义是 unsignedBigInteger,因此将其用于 users_id。
  • 请向我们展示用户表迁移

标签: php mysql laravel laravel-8


【解决方案1】:

你的外键需要和你的父键类型相同,users$table->id();中的父键是一个无符号大整数,所以你的外键也需要相同类型,改变:

$table->integer('users_id');
$table->foreign('users_id')->references('id')->on('users');

$table->unsignedBigInteger('users_id');
$table->foreign('users_id')->references('id')->on('users');

或者,使用foreignId

$table->foreignId('user_id')->constrained();

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 2018-02-04
    • 2022-01-25
    • 2020-12-02
    • 2020-12-19
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多