在Laravel中控制数据库是通过使用迁移。使用工匠创建迁移:
php artisan make:migration create_first_table --create=first_table
这将生成类CreateFirstTable。在up方法内,您可以创建列:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFirstTable extends Migration
{
public function up()
{
Schema::create('first_table', function (Blueprint $table) {
$table->increments('id');
$table->string('first_string_column_name');
$table->integer('secont_integer_column_name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('first_table');
}
}最后,要运行所有迁移类,您可以运行artisan命令:
php artisan migrate
这将在数据库中创建表和列。其他有用的迁移命令是:
php artisan migrate:rollback -回滚上一次数据库迁移
php artisan migrate:reset -回滚所有数据库迁移
php artisan migrate:refresh -重置并重新运行所有迁移
php artisan migrate:status -显示每次迁移的状态
修改现有表
有时,您需要更改现有的表结构(如renaming/deleting列)。您可以通过创建新的migration.AndInup方法来完成迁移。
//重命名列。
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('email', 'username');
});
}上面的例子中,将重命名email column的users table到username。而下面的代码username从users表中删除一列。
重要提示:要修改列,您需要向doctrine/dbal项目composer.json文件添加依赖项并运行composer update以反映更改。
//落柱
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('username');
});
}