php - Laravel,迁移,外键约束形成不正确
问题描述
我有两张桌子,即。产品和机构。有一个pid
自动递增的主键,一个id
在机构和产品中都是长度的varchar
主键。32
每个人都product
需要参考它,institution
因此我正在设置该institution
列products
并希望它是引用id
该机构的外键。
但是,我不断收到此错误,我花了整整一晚试图解决这个问题,但没有任何成功。
$ 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.
这是机构表的迁移,文件名是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();
});
}
虽然这是产品表的迁移,但文件名是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');
});
}
解决方案
$table->foreign('institution')
->references('id')
->on('institutions')
->onDelete('RESTRICT');
希望能帮助到你。
推荐阅读
- linux-device-driver - 为什么 DTBO 在加载时失败并在设备树的根目录中说没有符号。?
- java - 如何在回收站视图中显示图像?
- laravel-7 - Laravel sanctum 未经身份验证
- python - 类型。如何通过引用传递结构?
- android - android studio中的批量可绘制导入崩溃工作室
- python - 使用字典对语料库进行规范化
- python - 潜在狄利克雷分配 (LDA) 主题生成
- azure-cosmosdb - 无法使用基于 Cosmos DB 角色的访问控制获得读取/写入集合吞吐量的权限
- python - 用python删除矩阵中对角线上的值
- python - Pylint 检查器:未对字符串调用格式函数