![](/img/trans.png)
[英]SQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Table
[英]Laravel Error : SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'categories' already exists
我无法弄清楚问题是什么,2个表由于某种原因没有连接,我阅读了很多文章并尝试了很多东西仍然无法正常工作。
我想将帖子和类别表链接在一起,这样当我可以显示在发布的帖子中选择的类别时。
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name');
$table->text('description');
$table->integer('category_id');
$table->integer('price');
$table->integer('currency_id');
});
}
类别
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
});
}
这是我得到的错误:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'categories' already exists (SQL: create table
categories
(id
bigint unsigned not null auto_increment primary key,created_at
timestamp null,updated_at
timestamp null,name
varchar(255) not null ,post_id
bigint unsigned not null) 默认字符集 utf8mb4 collate 'utf8mb4_unicode_ci')
尝试使用migrate:refresh
artisan 命令完全刷新您的数据库。
php artisan migrate:refresh --seed
可能是数据库迁移在它可以注册到数据库的migrations
表中之前运行并失败。
问题:(到目前为止)
1)如上,一个migrate:refresh
整理出原来的错误
2) $table->bigInteger('post_id')->unsigned();
将不起作用,因为posts.id
是integer
而不是bigInteger
。
解决方案:
将您的post_id
定义更改为
$table->integer('post_id')->unsigned();
它说类别表已经存在。 所以你要做的是,如果你在开发环境中,你可以删除表并尝试它,或者你可以像下面的命令一样做。
像这样运行 artisan,它将删除所有表并迁移得更新鲜。
php artisan migrate:fresh
这对我有用。
答案很简单,您必须将帖子表中$table->increments('id')
更改为$table->id()
,因为如消息所述,外键必须引用主键。
您必须在posts表中使用bigIncrements
而不是integer
因为integer
的长度是4 字节,但bigIncrements
是8 字节,这可能会导致将来出现问题
你可能喜欢使用这条线
$table->foreignId('post_id')->constrained();
反而
$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
为简单起见
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.