如何向 Laravel 中的现有表添加新列

问题描述 投票:0回答:3

我正在表任务中添加新的列名称标题。但我收到一个错误,表明该表中不存在该列。任何人都可以帮助我解决该错误。这是我的代码:

php artisan make:migration add_title_to_tasks_table --table="tasks"
然后添加此代码

Schema::table('tasks', function (Blueprint $table) { 
  $table->string('title');
});

创建新的表文件

php mysql laravel-5
3个回答
4
投票

更改表并添加列。

     /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::table('tasks', function (Blueprint $table) {

            $table->string('title')->after('id');

           // to change column datatype or change it to `nullable` 
           // or set default values , this is just example

           $table->string('title')->default('Test')->change(); 

        });
    }

您可以在此处参考文档,Laravel 迁移


3
投票

对于那些刚接触 Laravel 并正在寻找解决方案的人,请按照以下步骤操作 1)。

php artisan make:migration add_title_to_tasks_table --table="tasks"

2)。编辑迁移文件夹中新创建的文件并添加以下内容。

public function up() {
    Schema::table('tasks', function (Blueprint $table) {

        $table->string('title')->after('id');

       // to change column datatype or change it to `nullable` 
       // or set default values , this is just example

       $table->string('title')->default('Test')->change(); 

    });
}

3)。运行迁移命令。

php 工匠迁移


1
投票

执行以下操作:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('tasks', function (Blueprint $table) {
       $table->string('title')->after('your-column-name');
    });
}

将“your-column-name”替换为您现有的列名称。

保存文件。从终端执行:

php artisan migrate

上述命令会将列添加到您的表中。

您收到该错误是因为您没有运行

migrate
命令。每当您创建迁移文件时,您必须执行上述命令才能看到数据库表中的更改。

此外,如果模型中不存在新列

$fillable
属性,您也必须将其添加到那里..

/**
 * The attributes that are mass assignable.
 *
 * @return  array
 */
protected $fillable = [
    'title', // <-- new column name
    // .. other column names
];

未能更新

$fillable
属性将导致
MassAssignmentExecption

© www.soinside.com 2019 - 2024. All rights reserved.