我有两张桌子。产品和机构。有一个主键
pid
哪个自动递增,还有一个
id
哪个是
varchar
属于
32
机构和产品的长度。
每个
product
需要参考其
institution
因此,我设置
机构
列在
products
并希望它是引用
身份证件
机构的。
然而,我一直在犯这个错误,我花了一整晚的时间试图找出这个问题,但没有成功。
$ php artisan migrate
Migration table created successfully.
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table `devbase`.`#sql-824_f23` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `institutions` add constraint `institutions_id_foreign` foreign key (`id`) references `institution` (`products`) on delete RESTRICT)
at [...]\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `devbase`.`#sql-824_f23` (errno: 150 "Foreign key constraint is incorrectly formed")")
[...]\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458
2 PDOStatement::execute()
[...]\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458
Please use the argument -v to see more details.
这是migration for institutions表,文件名是
2018_06_14_165449_create_institutions_table.php
public function up()
{
Schema::create('institutions', function (Blueprint $table) {
$table->increments('pid');
$table->string('id', 32)->unique();
$table->string('shortname', 16)->unique();
$table->text('fullname');
$table->string('logo', 100);
$table->timestamps();
});
}
而这是products表的迁移,文件名是
2018_06_15_031837_create_products_table.php
public function up()
{
Schema::enableForeignKeyConstraints();
Schema::create('products', function (Blueprint $table) {
$table->increments('pid');
$table->string('id', 32)->unique();
$table->string('url', 100)->unique();
$table->string('shortname', 16)->unique();
$table->string('institution', 32)->index()->nullable();
$table->timestamps();
$table->foreign('institution')
->references('institutions')
->on('id')
->onDelete('RESTRICT');
});
}