外键约束错误形成 - Laravel

时间:2017-08-13 11:24:04

标签: php mysql laravel laravel-5

我有两张桌子“剧院”和“立方体”。 “剧院”表已经创建。在“cubelists”表中,我将“area”和“stn”作为表“theatres”的外键。但是我错误地形成了外键约束。但我无法弄清楚错误。

Schema::create('theaters', function (Blueprint $table) {

    $table->string('theater_name');
    $table->string('area_name');
    $table->string('station');
    $table->primary(array('theater_name','area_name','station'));
    $table->text('address');
    $table->bigInteger('phno');
    $table->string('contact_person');

});

Schema::create('cubelists', function (Blueprint $table) {
    $table->string('mvie_name');
    $table->foreign('mvie_name')->references('movie_name')->on('movies');
    $table->string('thtr_name');
    $table->foreign('thtr_name')->references('theater_name')-
    >on('theaters');
    $table->string('area');
    $table->foreign('area')->references('area_name')->on('theaters');
    $table->string('stn');
    $table->foreign('stn')->references('station')->on('theaters');
    $table->primary(array('mvie_name','thtr_name','area','stn'));
    $table->string('type');
    $table->string('subtype');
    $table->date('validity');
    $table->string('show');

});

错误是

C:\xampp\htdocs\boras>php artisan migrate
Migration table created successfully.


  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1005 Can't create table `boras_cachii`.`#sql-a10_
  5a` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table
   `cubelists` add constraint cubelists_area_foreign foreign key (`area`) reference
  s `theaters` (`area_name`))



      [PDOException]
      SQLSTATE[HY000]: General error: 1005 Can't create table `boras_cachii`.`#sql-a10_
      5a` (errno: 150 "Foreign key constraint is incorrectly formed")

1 个答案:

答案 0 :(得分:0)

外键约束应引用候选键。我不知道 cubelist 意味着什么,但你可能想在"剧院"中引用主键。也就是说,可能希望一个外键约束引用三个列theater_name,area_name和station。不是每个列的单独约束。

MySQL可能会或可能不会让你逃避原本试图做的事情,但无论如何都不要这样做。搜索13.1.17.6 Using FOREIGN KEY Constraints以获取"不执行"。

相关问题