我有一张桌子“剧院”。其中(theater_name,area_name,station)是复合键。在表“cubelists”中,我有列(thtr_name,area,stn),它们将被引用(table_name,area_name,station)表“剧院”。 / p>
这里的问题是表“剧院”中的列 - (theater_name,area_name,station)的组合是唯一的,因为它是复合键。但每个列分别不是唯一的。
然后我如何从表“cubelists”中引用这些列?
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');
});
public function up()
{
//
Schema::create('cubelists', function (Blueprint $table) {
$table->string('mvie_name');
$table->foreign('mvie_name')->references('movie_name')->on('movies');
$table->string('thtr_name');
$table->string('area');
$table->string('stn');
$table->foreign(array('thtr_name','area','stn'))-
>references(array('theater_name','area_name','station'))-
>on('theaters');
$table->primary(array('mvie_name','thtr_name','area','stn'));
$table->string('type');
$table->string('subtype');
$table->date('validity');
$table->string('show');
});
}
如果我提供上述代码,我会收到错误
Migration table created successfully.
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `boras_cachii`.`#sql-a10_
112` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tabl
e `agreements` add constraint agreements_area_name_foreign foreign key (`area_nam
e`) references `cubelists` (`area`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `boras_cachii`.`#sql-a10_
112` (errno: 150 "Foreign key constraint is incorrectly formed")
答案 0 :(得分:2)
您必须首先创建表,然后创建外键。
Schema::create('cubelists', function (Blueprint $table) {
$table->string('mvie_name');
$table->string('area');
$table->string('stn');
$table->primary(array('mvie_name','thtr_name','area','stn'));
$table->string('type');
$table->string('subtype');
$table->date('validity');
$table->string('show');
$table->foreign(array('thtr_name','area','stn'))
->references(array('theater_name','area_name','station'))
->on('theaters');
$table->foreign('mvie_name')
->references('movie_name')
->on('movies');
});
theaters
表必须先迁移cubelists
,因为~/.zshrc
正在引用它。并确保外键列和引用列的类型或长度相同。