6

我正在做一个 laravel 项目,每次我更改表(添加或删除列)并运行php artisan migrate:refresh. 我收到此错误:

[Symfony\Component\Debug\Exception\FatalErrorException] 无法在写入上下文中使用方法返回值

尝试的解决方案:

  1. 运行composer dump-autoload(失败)
  2. 删除数据库中的表,删除迁移文件并重新启动(有效)

以前的迁移文件:

<?php

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

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id');
            $table->string('body');
            $table->timestamps();
        });
    }

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

更改的迁移文件:

    <?php

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

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('post_id');
            $table->string('body');
            $table->timestamps();
        });
    }

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

我在 up 函数的更改文件中添加了 user_id

4

3 回答 3

12

试试这个对我有用的命令

php artisan migrate:fresh

但是,要小心!此命令将从您的数据库中删除所有数据:

注意: migrate:fresh 命令将从数据库中删除所有表,然后执行 migrate 命令。

根据 Laravel 文档

于 2018-01-06T09:13:23.320 回答
1

试试这个火这个命令

php artisan make:migration add_user_id_to_comments_table --table=comments

这将创建一个新的迁移文件

$table->integer('user_id')->after('id');

然后使用

php artisan migrate
于 2018-10-11T07:40:07.740 回答
-1

刷新数据库并运行所有数据库种子...

php artisan migrate:fresh --seed

阅读文档

于 2021-11-04T13:16:18.467 回答