无法在Laravel Migrations中添加外键约束

问题描述 投票:0回答:2

我目前有两张桌子SymbolsPrices。我目前正在为Prices创建一个迁移,并向引用Prices.symbol_idSymbols.id添加一个FK约束。这是Prices迁移:

        $table->increments('id');
        ...
        ...
        $table->integer('symbol_id');
        $table->foreign('symbol_id')
            ->references('id')->on('Symbols')
            ->onDelete('cascade’);

Symbols.id只是一个$table->increments(‘id’);

但是,当我运行迁移时,会发生以下情况:

  [Illuminate\Database\QueryException]                                                 
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter   
  table `Prices` add constraint prices_symbol_id_foreign foreign key (`symbol_id`) re  
  ferences `Symbols` (`id`))                  

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

有什么想法吗?

laravel pdo migration database-migration
2个回答
1
投票

进行新的迁移

php artisan make:migration update_prices_table

架构:

 public function up()
 {
    Schema::table('Prices', function (Blueprint $table) {
        $table->integer('symbol_id)->unsigned();
        $table->foreign('symbol_id')
        ->references('id')->on('Symbols')
        ->onDelete('cascade’);
    });
}

0
投票

如果主键的类型为bigIncrements,请确保使用bigInteger作为外键的数据类型

© www.soinside.com 2019 - 2024. All rights reserved.