【问题标题】:Foreign key codes are not working in migrations of Laravel 8外键代码在 Laravel 8 的迁移中不起作用
【发布时间】:2021-04-21 12:21:42
【问题描述】:

我试图创建一个外键,但是它不起作用。

帖子迁移

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string("title", 60);
            $table->string("description", 200);
            $table->text("content");
            $table->string("photo");
            $table->unsignedBigInteger('user_id');
            $table->timestamps();
            $table->foreign("user_id")->references("id")
                ->on("users")->onDelete("cascade");
        });
    }
    
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

用户迁移

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string("name", 30);
            $table->string("email")->unique();
            $table->string("password");
            $table->string("username")->unique();
            $table->timestamps();
        });
    }
    
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

我正在尝试为应该通过外键与用户 ID 连接的帖子创建一个“user_id”列。但是,当我迁移时,我收到如下错误

照亮\数据库\查询异常

SQLSTATE[HY000]:一般错误:1005 无法创建表 mytest_db.posts (errno: 150 "外键约束不正确 形成”)(SQL:改变表posts添加约束 posts_user_id_foreign 外键 (user_id) 引用 users (id) 删除级联)

在 W:\domains\mytest.uz\vendor\laravel\framework\src\Illuminate\Database\Connection.php:678 674▕ // 如果尝试运行查询时发生异常,我们将格式化错误 675▕ // 包含与 SQL 的绑定的消息,这将使该异常成为 676▕ // 对开发人员更有帮助,而不仅仅是数据库的错误。 677▕ catch (Exception $e) { ➜ 678▕ throw new QueryException( 679▕$查询,$this->prepareBindings($bindings),$e 680▕); 681▕} 682▕

1
W:\domains\mytest.uz\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471 PDOException::("SQLSTATE[HY000]: 一般错误: 1005 无法创建表mytest_db.posts (errno: 150 "外键约束 格式不正确")")

2
W:\domains\mytest.uz\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471 PDOStatement::execute()

【问题讨论】:

  • 迁移运行的顺序是什么? CreateUsersTable 应该在 CreatePostsTable 之前运行
  • 谢谢你,Erich,你帮了我很多!!!

标签: php mysql laravel foreign-keys laravel-8


【解决方案1】:

不能在尚不存在的表上定义外键。

Laravel 按文件名顺序执行迁移,在迁移名称前加上时间戳。 确保CreatePostsTable 迁移在CreateUsersTable 迁移之后

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 2020-02-20
    • 2021-02-21
    • 2019-08-29
    • 2020-06-05
    • 2017-06-18
    相关资源
    最近更新 更多