mysql - Laravel 迁移外键不起作用
问题描述
我正在laravel上创建一个新的应用程序,我正在编写迁移,我想为我的列设置外键,所以我这样做如下:
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->integer('type_id');
$table->string('name');
$table->integer('status_id')->default(0);
$table->integer('category_id')->default(0);
$table->integer('store_id');
$table->timestamps();
$table->foreign('status_id')->references('id')->on('product_statuses');
$table->index('status_id');
$table->foreign('type_id')->references('id')->on('product_types');
$table->index('type_id');
$table->foreign('category_id')->references('id')->on('product_categories');
$table->index('category_id');
$table->foreign('store_id')->references('id')->on('stores');
$table->index('store_id');
但是这些不起作用,因为我在其中检查phpmyadmin
它让我插入任何数字而不是来自status_id
例如的项目,当我在design
选项卡中检查它时,我看不到表之间的关系。#编辑
添加product_types
迁移:
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('product_types', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
关于我使用 wamp 和 mysql v8 的引擎,我认为它支持 fk 功能
解决方案
正如你在评论中所说:
我看到的是,在表格上的 phpmyadmin 中有一个列在写 :Type :MyISAM 。引擎的意思是一样的吗?
您的数据库默认引擎是不支持关系功能的 MyISAM。
要解决此问题,您可以编辑config/database.php
文件,搜索mysql
条目并更改:
'engine' => null,
至
'engine' => 'InnoDB',
然后你必须重新创建表。
如果出于任何原因无法删除并重新创建表,则可以创建新迁移以更改现有表。IE:
public function up()
{
$tables = [
'product_types',
'products',
];
foreach ($tables as $table) {
DB::statement('ALTER TABLE ' . $table . ' ENGINE = InnoDB');
}
}
另一件事,外键列的数据类型必须匹配相关列的相同数据类型。
由于$table->id()
是$table->bigIncrements('id')
laravel 最新版本文档中所述的别名,因此您应该使用:
$table->unsignedBigInteger('type_id');
$table->foreign('type_id')->references('id')->on('product_types');
还要注意顺序:首先创建列,然后是 fk 引用(而不是相反)。
参考:https ://laravel.com/docs/8.x/migrations#foreign-key-constraints
推荐阅读
- c# - 如果 Json 键之一包含点,如何为 Json 序列化声明匿名类型?
- java - Java 8 无法在 Macos Catalina 中写入文件
- ios - 从 UIScrollview 中删除内容和框架布局指南
- powershell - 在 Powershell 中,我如何使用变量从文件夹权限中删除组
- c - 指针取消引用的不同行为
- react-native - 从头开始显示字符串 React Native TextInput
- javascript - 链接未打开模式上的数据切换
- vuejs2 - vue2 router - 不经过root直接访问路由器链接
- twitter-bootstrap - 如何在以下模态中修复 Col 间距
- docker - 如何在 nginx docker 容器中将干净的 url 重写为 .html?