Far*_*had 4 mysql migration 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');
Run Code Online (Sandbox Code Playgroud)
但这些都不起作用,因为我检查它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();
});
}
Run Code Online (Sandbox Code Playgroud)
关于引擎,我将 wamp 与 mysql v8 一起使用,我认为它支持 fk 功能
正如您在评论中所说:
我看到的是,在表的 phpmyadmin 中有一列正在写入 :Type :MyISAM 。发动机的意思是一样的吗?
您的数据库默认引擎是 MyISAM,它不支持关系功能。
要解决您可以编辑config/database.php文件的问题,请搜索mysql条目并更改:
'engine' => null,
Run Code Online (Sandbox Code Playgroud)
到
'engine' => 'InnoDB',
Run Code Online (Sandbox Code Playgroud)
然后你必须重新创建表。
如果出于任何原因无法删除和重新创建表,则可以创建新迁移来更改现有表。IE:
public function up()
{
$tables = [
'product_types',
'products',
];
foreach ($tables as $table) {
DB::statement('ALTER TABLE ' . $table . ' ENGINE = InnoDB');
}
}
Run Code Online (Sandbox Code Playgroud)
另一件事,外键列的数据类型必须与相关列的相同数据类型匹配。
由于$table->id()是$table->bigIncrements('id')laravel 最新版本文档中所述的别名,您应该使用:
$table->unsignedBigInteger('type_id');
$table->foreign('type_id')->references('id')->on('product_types');
Run Code Online (Sandbox Code Playgroud)
还要注意顺序:首先创建列,然后创建 fk 引用(而不是相反)。
参考:https : //laravel.com/docs/8.x/migrations#foreign-key-constraints
| 归档时间: |
|
| 查看次数: |
504 次 |
| 最近记录: |