在Laravel迁移中给现有表添加新列。
在Laravel迁移中给现有表添加新列。
我想在我的现有表users
中添加一些新列。
我已经搜索了相关内容,并使用命令php artisan make:migration add_columns_to_users
创建了迁移。
add_columns_to_users.php
public function up() { Schema::table('users', function($table) { $table->string('address'); $table->string('city'); $table->string('tribe'); $table->string('country'); $table->integer('student_id'); $table->string('tribe_university_name'); $table->string('student_program_of_study'); $table->string('faculty'); $table->string('level'); }); } public function down() { Schema::table('users', function($table) { $table->dropColumn('address'); $table->dropColumn('city'); $table->dropColumn('tribe'); $table->dropColumn('country'); $table->dropColumn('student_id'); $table->dropColumn('tribe_university_name'); $table->dropColumn('faculty'); $table->dropColumn('level'); }); }
创建后,我运行了php artisan migrate
命令。
但是我得到了相同的错误:
基本表或视图已存在:1050表“users”已存在(SQL:create table
users
(id
int unsigned not null auto_increment primary key,name
varchar(255)not null,password
varchar(255)not null,remember_token
varchar(100)null,created_at
timestamp null,updated_at
timestamp null)默认字符集为utf8 collate utf8_unicode_ci)
用户表的完整名称为2014_10_12_000000_create_users_table.php
,另一个名称为2019_04_11_074552_add_column_to_users.php
该如何解决?
我的主要问题是如何在现有表中添加新列?
如果您检查错误跟踪:
基本表或视图已存在:1050表'用户'已存在
这意味着用户表已经存在,因此当您运行迁移时,它会尝试创建已经在数据库中创建的表。
注意:不要忘记备份您的数据库
删除用户表和从迁移表中删除用户条目。
之后,执行迁移Artisan命令:php artisan migrate
现在,另一个问题是:如何在现有表中添加新列?
您必须使用此命令创建一个表:
php artisan make:migration create_users_table
您得到的输出如下所示:
已创建迁移:2019_04_12_070152_create_users_table
您的迁移结构如下:
public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); }
现在,您想要向现有用户表添加新列
php artisan make:migration add_phone_number_to_users_table --table=users
使用Schema::table()
方法(因为您正在访问现有表,而不是创建新表)。您可以像这样添加列:
public function up() { Schema::table('users', function (Blueprint $table) { $table->string('phonenumber')->after('name'); // use this for field after specific column. }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('phonenumber'); }); }
之后,您可以运行迁移:php artisan migrate
您的新列(电话号码
)现在已添加到现有的用户表中,您可以在数据库中查看。
如果您仍然有任何疑问,请参阅此视频