繁体   English   中英

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

[英]How to add new column to existing table in laravel

我在表任务中添加了新的列名标题。 但是我收到一个错误,该列在该表中不存在。 谁能帮助我解决该错误。 这是我的代码:

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

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

到创建的新表文件

要更改表并添加列。

     /**
     * 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 Migration

对于那些刚接触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的工匠迁移

请执行下列操作:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('tasks', function (Blueprint $table) {
       $table->string('title')->after('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属性将导致MassAssignmentExecption

希望这可以帮助你。 编码愉快。 干杯。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM