我已经创建了一个表'create_courses_table',但是当我尝试迁移该新表时,我从已经迁移的上一个表中得到了以下错误:
Migrating: 2020_03_04_141200_create_role_user_pivot_table
Illuminate\Database\QueryException
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'role_user' already exists (SQL: create table `role_user` (`user_id` int unsigned not null, `role_id` int unsigned not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:669
665| // If an exception occurs when attempting to run a query, we'll format the error
666| // message to include the bindings with SQL, which will make this exception a
667| // lot more helpful to the developer instead of just the database's errors.
668| catch (Exception $e) {
> 669| throw new QueryException(
670| $query, $this->prepareBindings($bindings), $e
671| );
672| }
673|
+9 vendor frames
10 database/migrations/2020_03_04_141200_create_role_user_pivot_table.php:22
Illuminate\Support\Facades\Facade::__callStatic("create")
+22 vendor frames
33 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
我认为我的数据透视表有错误吗?我不太确定自己做错了什么。其代码如下:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRoleUserPivotTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
感谢您的帮助。
答案 0 :(得分:0)
在up方法中添加一个检查,以确认运行迁移之前表是否不存在。
public function up()
{
if (!Schema::hasTable('role_user')) {
Schema::create('role_user', function (Blueprint $table) {
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles');
});
}
}
答案 1 :(得分:0)
根据您对问题的评论,我认为将迁移存储在迁移表中时出了点问题。
在数据库上运行以下查询。如果它返回0,请继续我的回答。 如果它返回1(或更多),请忽略我的回答,该错误在其他地方:
SELECT COUNT(*) FROM migrations WHERE migration = '2020_03_04_141200_create_role_user_pivot_table';
要解决此问题,您可以将迁移手动添加到表中:
只需在名为migrations
的表中添加一个新元组,并在.php
列中添加文件名(不包含2020_03_04_141200_create_role_user_pivot_table
,ergo migration
)和一个{{1} }-数字,比表格中的最高价格高1。
Ergo:这样做:
获取增加的批号:
batch
然后手动插入您的迁移(用上一个查询的结果替换SELECT MAX(batch)+1 FROM migrations
)
42