gpt4 book ai didi

laravel - 迁移:无法添加外键约束

转载 作者:行者123 更新时间:2023-12-03 04:13:45 31 4
gpt4 key购买 nike

我正在尝试在 Laravel 中创建外键,但是当我使用 artisan 迁移表时,出现以下错误:

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `priorities` add constraint priorities_user_id_foreign foreign
key (`user_id`) references `users` (`id`))

我的迁移代码如下:

优先迁移文件

public function up()
{
//
Schema::create('priorities', function($table) {
$table->increments('id', true);
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->string('priority_name');
$table->smallInteger('rank');
$table->text('class');
$table->timestamps('timecreated');
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
Schema::drop('priorities');
}

用户迁移文件

public function up()
{
//
Schema::table('users', function($table)
{
$table->create();
$table->increments('id');
$table->string('email');
$table->string('first_name');
$table->string('password');
$table->string('email_code');
$table->string('time_created');
$table->string('ip');
$table->string('confirmed');
$table->string('user_role');
$table->string('salt');
$table->string('last_login');

$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
Schemea::drop('users');
}

关于我做错了什么的任何想法,我想现在就得到这个,因为我需要创建很多表,例如用户、客户、项目、任务、状态、优先级、类型、团队。理想情况下,我想创建用外键保存这些数据的表,即 clients_projectproject_tasks 等。

希望有人可以帮助我开始。

最佳答案

分两步添加,最好不要签名:

public function up()
{
Schema::create('priorities', function($table) {
$table->increments('id', true);
$table->integer('user_id')->unsigned();
$table->string('priority_name');
$table->smallInteger('rank');
$table->text('class');
$table->timestamps('timecreated');
});

Schema::table('priorities', function($table) {
$table->foreign('user_id')->references('id')->on('users');
});

}

关于laravel - 迁移:无法添加外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22615926/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com