向迁移中的现有表添加新列 [英] Add a new column to existing table in a migration
问题描述
我不知道如何使用Laravel框架向现有数据库表中添加新列.
I can't figure out how to add a new column to my existing database table using the Laravel framework.
我尝试使用...来编辑迁移文件
I tried to edit the migration file using...
<?php
public function up()
{
Schema::create('users', function ($table) {
$table->integer("paid");
});
}
在终端中,我执行php artisan migrate:install
和migrate
.
如何添加新列?
推荐答案
要创建迁移,可以在Artisan CLI上使用migration:make命令.使用特定名称以避免与现有模型冲突
To create a migration, you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models
对于Laravel 3:
for Laravel 3:
php artisan migrate:make add_paid_to_users
对于Laravel 5 +:
for Laravel 5+:
php artisan make:migration add_paid_to_users_table --table=users
然后,您需要使用Schema::table()
方法(在访问现有表而不是创建新表时).您可以添加这样的列:
You then need to use the Schema::table()
method (as you're accessing an existing table, not creating a new one). And you can add a column like this:
public function up()
{
Schema::table('users', function($table) {
$table->integer('paid');
});
}
并且不要忘记添加回滚选项:
and don't forget to add the rollback option:
public function down()
{
Schema::table('users', function($table) {
$table->dropColumn('paid');
});
}
然后,您可以运行迁移:
Then you can run your migrations:
php artisan migrate
Laravel 3的文档都对此进行了详细介绍.
This is all well covered in the documentation for both Laravel 3:
- Schema Builder
- Migrations
对于Laravel 4/Laravel 5:
And for Laravel 4 / Laravel 5:
- Schema Builder
- Migrations
使用$table->integer('paid')->after('whichever_column');
将该字段添加到特定列之后.
use $table->integer('paid')->after('whichever_column');
to add this field after specific column.
这篇关于向迁移中的现有表添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!