【问题标题】:How to add new column to existing table in laravel如何在laravel中向现有表中添加新列
【发布时间】:2018-08-14 06:07:42
【问题描述】:

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

php artisan make:migration add_title_to_tasks_table --table="tasks" 然后加上这段代码

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

到创建的新表文件

【问题讨论】:

标签: php mysql laravel-5


【解决方案1】:

改变表并添加列。

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

【讨论】:

  • 得到这个错误:“SQLSTATE[HY000]:一般错误:1表任务没有名为标题的列(SQL:插入“任务”(“标题”,“描述”,“用户ID”, "updated_at", "created_at" ▶"
  • 您的迁移运行成功了吗?将表结构与您的要求相匹配。
  • 为了修改现有的列,必须安装一个依赖项。Doctrine/DBALlaravel.com/docs/5.6/migrations#modifying-columns
  • 我安装了依赖但仍然是同样的问题
  • @NishaSharma,如果您的评论与我的回答/帖子有关,请在此处添加您的评论。我很难识别您是指我的帖子还是 Mayank 的帖子
【解决方案2】:

对于 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 工匠迁移

【讨论】:

  • 谢谢!这就是我一直在寻找的。​​span>
【解决方案3】:

执行以下操作:

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

希望这对您有所帮助。快乐编码。干杯。

【讨论】:

    猜你喜欢
    • 2013-05-23
    • 2021-11-11
    • 2021-05-13
    • 2015-12-25
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2017-10-02
    • 2021-08-15
    相关资源
    最近更新 更多