【问题标题】:What's wrong with Laravel foreign key?Laravel 外键有什么问题?
【发布时间】:2016-05-25 00:17:15
【问题描述】:

我正在尝试使用 Laravel 的迁移创建外键。

 Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsinged();
        $table->string('title');
        $table->longText('body');
        $table->timestamp('published_at');
        $table->timestamps();

    });


    Schema::table('articles', function($table) {
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

    });

当我执行php artisan migrate 时出现以下错误

[照亮\数据库\查询异常]
SQLSTATE[HY000]:一般错误:1215 无法添加外键约束 (SQL:修改表laravel_articles添加约束 article_user_id_foreign 外键 (user_id ) 参考 laravel_users (id) 删除级联)`

【问题讨论】:

  • @MarkBaker 不起作用!!
  • 这是同一个迁移吗?

标签: php mysql laravel


【解决方案1】:

您的方法名称有误。应该是unsigned() 而不是unsinged()

Schema::create('articles', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->string('title');
    $table->longText('body');
    $table->timestamp('published_at');
    $table->timestamps();
});

Schema Builder 使用Fluent 链接方法,即使链接方法unsinged 不存在也不会引发异常。尽管有错字,articles 表仍将被创建,但 user_id 列将是有符号整数,并且由于 users 表中的 id 列是无符号整数,它将阻止创建约束.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 2013-05-31
    相关资源
    最近更新 更多