Laj*_*rek 36 database-migration laravel laravel-4
表'用户':
|id|name|address|post_code|deleted_at|created_at|
Run Code Online (Sandbox Code Playgroud)
我想在'id'和'deleted_at'之间添加列'phone_nr'
是否可以通过Laravel 4.1迁移?
Jam*_*ord 114
是.使用创建新迁移php artisan migrate:make update_users_table
.
然后使用以下table
命令(如果您使用的是MySQL!):
Schema::table('users', function($table)
{
$table->string('phone_nr')->after('id');
});
Run Code Online (Sandbox Code Playgroud)
完成迁移后,保存并运行它php artisan migrate
,您的表格将会更新.
文档:https://laravel.com/docs/4.2/migrations#column-modifiers
Nic*_*ick 11
詹姆斯的答案仍然是正确的.但是,Laravel 5略微改变了make migration语法:
php artisan make:migration add_google_auth_to_users_table --table=users
Run Code Online (Sandbox Code Playgroud)
(我知道这个问题被标记为Laravel 4,但问题的排名相当高;))
小智 11
如果您需要在 laravel 8 中的特定列之后添加几列:
使用 MySQL 数据库时,可以使用 after 方法在模式中的现有列之后添加列:
$table->after('password', function ($table) {
$table->string('address_line1');
$table->string('address_line2');
$table->string('city');
});
Run Code Online (Sandbox Code Playgroud)
https://laravel.com/docs/8.x/migrations#column-order
对于想知道@rahulsingh 关于在单个特定列后背靠背添加多个列的查询的其他人:
$table->integer('col1')->after('ref_col');
$table->integer('col2')->after('what');
Run Code Online (Sandbox Code Playgroud)
您只需按相反顺序编写新字段即可完成此操作,例如:
$table->integer('col4')->after('ref_col');
$table->integer('col3')->after('ref_col');
$table->integer('col2')->after('ref_col');
$table->integer('col1')->after('ref_col');
Run Code Online (Sandbox Code Playgroud)
当您运行此迁移时,您会发现您的新字段col
, col2
, ... 在参考字段之后按照您的预期顺序排列ref_col
。
不幸的是,没有before()
在现有字段之前添加字段的功能。(如果存在,我们可以按实际顺序保留上述语句。)
您不能对尚不存在的字段进行链接,例如:
$table->integer('col1')->after('ref_col');
$table->integer('col2')->after('col1');
$table->integer('col3')->after('col2');
$table->integer('col4')->after('col3');
Run Code Online (Sandbox Code Playgroud)
这是因为迁移蓝图被编译为单个查询,因此作为一个查询执行,因此在添加col2
数据库引擎时会抱怨col1
不存在。