当前位置:Gxlcms > PHP教程 > laravel数据迁移问题

laravel数据迁移问题

时间:2021-07-01 10:21:17 帮助过:20人阅读

使用数据迁移创建了一个表,表里已经有数据了,这个时候想要添加字段,或修改字段,或删除字段,要怎么操作?

回复内容:

使用数据迁移创建了一个表,表里已经有数据了,这个时候想要添加字段,或修改字段,或删除字段,要怎么操作?

重新建立migration文件,通常我们建立的migration文件有两种,一种是创建表,另一种是修改表,比如说你要创建一个表,打个比方你要创建users表,你会这么写:

php artisan make:migration create_users_table --create=users

如果你已经执行了php artisan migrate, 并且已经插入了一些数据,这时候你如果想修改,添加或者删除当中的字段,那么你需要重新建立一个migration文件,打个比方,你现在要添加个email字段

php artisan make:migration add_email_column_to_users_table --table=users

将你要的内容写在add_email_column_to_users_table文件中,然后在执行 php artisan migrate

至于migration文件中的内容的写法都一样,文档中非常清楚的写着,或者你也可以看下我这篇教程:

http://www.zhoujiping.com/scratch/fetching-data.html

另外你看下数据库中的migraitons表中的记录,你应该会想通你之前出错的原因

添加字段

Schema::table('users', function ($table) {
    $table->string('email');
});

修改字段

Schema::table('users', function ($table) {
    $table->string('name', 50)->change();
});

重命名字段

Schema::table('users', function ($table) {
    $table->renameColumn('from', 'to');
});

移除字段

Schema::table('users', function ($table) {
    $table->dropColumn('votes');
});

人气教程排行