社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  MAHDI ABDULSAHIB  »  全部回复
回复总数  1
8 年前
回复了 MAHDI ABDULSAHIB 创建的主题 » mysql-错误1215:无法添加外键约束[重复]

当使用laravel迁移时尝试生成外键时

比如这个例子:

用户表

    public function up()
{
    Schema::create('flights', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->TinyInteger('color_id')->unsigned();
        $table->foreign('color_id')->references('id')->on('colors');
        $table->timestamps();
    });
}

颜色表

    public function up()
{
    Schema::create('flights', function (Blueprint $table) {
        $table->increments('id');
        $table->string('color');
        $table->timestamps();
    });
}

有时物业不起作用

[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

发生此错误的原因是[用户表]中的外键(类型)不同于[颜色表]中的主键(类型)

若要解决此问题,应更改[颜色表]中的主键

$table->tinyIncrements('id');


使用主键时 $table->Increments('id');

你应该用 Integer 作为外键

    $table-> unsignedInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

使用主键时 $表->tinyincrements('id');

你应该用 unsignedTinyInteger 作为外键

    $table-> unsignedTinyInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

使用主键时 $table->smallIncrements('id');

你应该用 unsignedSmallInteger 作为外键

    $table-> unsignedSmallInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

使用主键时 $table->mediumIncrements('id');

你应该用 unsignedMediumInteger 作为外键

    $table-> unsignedMediumInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');