使用外键 Laravel 创建 table 时出错
Error creating table with foreign key Laravel
这是我的第一个 table 迁移文件:
public function up()
{
Schema::create('produits', function (Blueprint $table) {
$table->id();
$table->string('nom',255)->unique();
$table->string('photo')->default('default.png');
$table->longText('description');
$table->float('prix');
$table->unsignedBigInteger('categorie_id');
$table->foreign('categorie_id')->refrences('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
}
这是我的第二个 table 迁移文件:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('nom',255)->unique();
$table->timestamps();
});
}
这是我遇到的错误:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'produits' already exists (SQL: create table `produits` (`id` bigint unsigned not null auto_increment primary key, `nom` varchar(255) not null, `photo` varchar(255) not null default 'default.png', `description` longtext not null, `prix` double(8, 2) not null, `categorie_id` bigint unsigned not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')
我都试过了:php artisan migrate
,php artisan migrate:refresh
几乎,你可以尝试php artisan migrate:fresh
,这将删除所有表并创建新表。
你的迁移有drop方法吗?
public function down()
{
statement('DROP TABLE categories');
}
您可以尝试从数据库中删除 tables,并且在您再次 运行 迁移之前,请确保首先创建 类别 迁移。
如果您首先创建了 produits 迁移,它将不起作用,因为当迁移为 运行 时,produits table首先创建,它不会找到尚不存在的引用 table。因此,不会创建外键约束。
这是我的第一个 table 迁移文件:
public function up()
{
Schema::create('produits', function (Blueprint $table) {
$table->id();
$table->string('nom',255)->unique();
$table->string('photo')->default('default.png');
$table->longText('description');
$table->float('prix');
$table->unsignedBigInteger('categorie_id');
$table->foreign('categorie_id')->refrences('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
}
这是我的第二个 table 迁移文件:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('nom',255)->unique();
$table->timestamps();
});
}
这是我遇到的错误:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'produits' already exists (SQL: create table `produits` (`id` bigint unsigned not null auto_increment primary key, `nom` varchar(255) not null, `photo` varchar(255) not null default 'default.png', `description` longtext not null, `prix` double(8, 2) not null, `categorie_id` bigint unsigned not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')
我都试过了:php artisan migrate
,php artisan migrate:refresh
几乎,你可以尝试php artisan migrate:fresh
,这将删除所有表并创建新表。
你的迁移有drop方法吗?
public function down()
{
statement('DROP TABLE categories');
}
您可以尝试从数据库中删除 tables,并且在您再次 运行 迁移之前,请确保首先创建 类别 迁移。 如果您首先创建了 produits 迁移,它将不起作用,因为当迁移为 运行 时,produits table首先创建,它不会找到尚不存在的引用 table。因此,不会创建外键约束。