Ara*_*man 6 php mysql migration laravel laravel-5.5
我想users在 laravel 的现有表中添加一些新列。
我已经在谷歌上搜索过了,在这些搜索之后,我已经使用命令创建了迁移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');
});
}
Run Code Online (Sandbox Code Playgroud)
创建后,我运行此命令php artisan migrate。
但得到了同样的错误:
基表或视图已存在:1050 表“用户”已存在(SQL:创建表
users(idint unsigned not null auto_increment primary key,namevarchar(255) not null,passwordvarchar(255) not null,remember_tokenvarchar (100) null,created_attimestamp null,updated_attimestamp null) 默认字符集 utf8 collate utf8_unicode_ci)
用户表的全名,2014_10_12_000000_create_users_table.php另一个名称是2019_04_11_074552_add_column_to_users.php
如何解决这个问题?
我的主要查询是如何在现有表中添加新列?
Udh*_*iya 13
如果您检查错误跟踪:
基表或视图已存在:1050 表 'users' 已存在
这意味着users 表已经存在,因此当您运行迁移时,它会尝试创建一个已在您的数据库中创建的表。
笔记:不要忘记先备份您的数据库
从数据库中删除用户表也会从迁移中删除用户条目表中。
之后,执行 migrate Artisan 命令:php artisan migrate
现在另一个您的问题是:如何在现有表中添加新列?
您必须使用以下命令创建一个表:
php artisan make:migration create_users_table
Run Code Online (Sandbox Code Playgroud)
你得到的输出是这样的:创建迁移: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();
});
}
Run Code Online (Sandbox Code Playgroud)
现在您想在现有用户表中添加新列
php artisan make:migration add_phone_number_to_users_table --table=users
Run Code Online (Sandbox Code Playgroud)
使用该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');
});
}
Run Code Online (Sandbox Code Playgroud)
之后,您可以运行迁移: php artisan migrate
您的新列 ( phonenumber) 现在已添加到您现有的用户表中,您可以在数据库中查看该。
如果您还有任何疑问,请观看此视频