首页 > 解决方案 > Laravel 错误:SQLSTATE [42S01]:基表或视图已存在:1050 表“类别”已存在

问题描述

我无法弄清楚问题是什么,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]:基表或视图已存在:1050 表“类别”已存在(SQL:创建表categoriesid bigint unsigned not null auto_increment 主键,created_at timestamp null,updated_attimestamp null,namevarchar(255) not null,post_idbigint unsigned not null ) 默认字符集 utf8mb4 collat​​e 'utf8mb4_unicode_ci')

标签: phpmysqllaraveleloquent

解决方案


migrate:refresh尝试使用artisan 命令完全刷新数据库。

php artisan migrate:refresh --seed

可能是数据库迁移在注册到migrations数据库表之前运行并失败了。


问题:(到目前为止)

1) 如上所述,amigrate:refresh整理出原来的错误

2)$table->bigInteger('post_id')->unsigned();不会像posts.idaninteger而不是 a那样工作bigInteger

解决方案:

post_id将您的定义更改为

$table->integer('post_id')->unsigned();

推荐阅读