无法进行迁移。获取与外键相关的错误

Unable to make a migration. Getting errors related to foreign keys

第一个迁移文件:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

第二次迁移文件:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements("post_id");
            $table->bigInteger("author_id");
            $table->string("title");
            $table->string("short_title");
            $table->string("img")->nullable();
            $table->text("descr");
            $table->timestamps();

            $table->foreign("author_id")->references("id")->on("users");
        });
    }

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

在我 运行 php artisan migrate 命令后我收到错误。

Illuminate\Database\QueryException 

  SQLSTATE[HY000]: General error: 1005 Can't create table 
`laralove`.`posts` (errno: 150 "Foreign key constraint is 
incorrectly formed") (SQL: alter table `posts` add constraint `posts_author_id_foreign` foreign key (`author_id`) references `users` (`id`))

  at C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
    // If an exception occurs when attempting to run a query, we'll format the error
       // message to include the bindings with SQL, which will make this exception a
        // lot more helpful to the developer instead of just the database's errors.
        catch (Exception $e) {
          throw new QueryException(
               $query, $this->prepareBindings($bindings), $e
        }


  1   C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485
      PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `laralove`.`posts` (errno: 150 "Foreign key constraint is incorrectly formed")")

  2   C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485
      PDOStatement::execute()
PS C:\xampp\htdocs\laralove> php artisan config:cache
Configuration cache cleared!
Configuration cached successfully!
PS C:\xampp\htdocs\laralove> php artisan migrate     
Migrating: 2021_06_13_195343_create_posts_table



    Illuminate\Database\QueryException 
    
      SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'posts' already exists (SQL: create table `posts` (`post_id` bigint unsigned not null auto_increment primary key, `author_id` bigint not null, `title` varchar(255) not null, `short_title` varchar(255) not null, `img` varchar(255) null, `descr` text not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8 collate 'utf8_general_ci' engine = InnoDB)
    
      at C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
            // If an exception occurs when attempting to run a query, we'll format the error
            // message to include the bindings with SQL, which will make this exception a
             // lot more helpful to the developer instead of just the database's errors.
                    $query, $this->prepareBindings($bindings), $e
               );                            ings($bindings), $e
            }


  1   C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485    work\src\Illuminate\Database\Connectio
      PDOException::("SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'posts' already er view already exists: 1050 Table 'posxists")

  2   C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connectiowork\src\Illuminate\Database\Connection.php:485    
      PDOStatement::execute()

更新 1

@miken32 建议执行命令 php artisan migrate:rollback
出于某种原因,我收到以下错误:

Illuminate\Database\QueryException 

  SQLSTATE[HY000] [2002]   , ..      .
 (SQL: select max(`batch`) as aggregate from `migrations`)

  at C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
    // If an exception occurs when attempting to run a query, we'll format the error
    // message to include the bindings with SQL, which will make this exception a
    // lot more helpful to the developer instead of just the database's errors.
catch (Exception $e) {
            throw new QueryException(
              $query, $this->prepareBindings($bindings), $e
           );
       }
  

  1   C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDOException::("SQLSTATE[HY000] [2002]   , ..      .
")

  2   C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDO::__construct("mysql:host=localhost;port=3306;dbname=laralove", "root", "", [])

UPD 2

我已经应用了@Amir Daneshkar 建议的更改

以前的错误消失了,但出现了新的错误。我不知道这里有什么问题。

新错误:

Illuminate\Database\QueryException 

  SQLSTATE[HY000] [2002]   , ..      .
 (SQL: select * from information_schema.tables where table_schema = laralove and table_name = migrations and table_type = 'BASE TABLE')

  at C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
    688▕         // If an exception occurs when attempting to run a query, we'll format the error
    689▕         // message to include the bindings with SQL, which will make this exception a   
    690▕         // lot more helpful to the developer instead of just the database's errors.     
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕

    689▕         // message to include the bindings with SQL, which will make this exception a
    690▕         // lot more helpful to the developer instead of just the database's errors.
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕

  1   C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDOException::("SQLSTATE[HY000] [2002]   , ..      .
")

  2   C:\xampp\htdocs\laralove\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDO::__construct("mysql:host=localhost;port=3306;dbname=laralove", "root", "", [])

UPD 2.1.
我配置了 .env 和 database.php 文件

.env 文件:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laralove
DB_USERNAME=root
DB_PASSWORD=

'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'url' => env('DATABASE_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'laralove'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_general_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => "InnoDB",
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],
//...
]

将帖子迁移 post_idauthor_id 更改为:

$table->id('post_id');
$table->unsignedBigInteger('author_id');
...

我记得 Laravel id 字段需要是 unsignedBigInts 并且定义 id 字段的正确格式也是这样的:

$table->unsignedBigInteger('id')->unique()->autoIncerement() ;

里面有个宏$table->id('column_name');

更新 这样做之后 运行 php artisan migrate:fresh ,如果它抛出错误,请尝试删除数据库并重新创建它