Laravel框架数据库迁移的优点是什么?如何使用?
发布时间:2022-04-14 13:25:25 所属栏目:语言 来源:互联网
导读:在学习Laravel框架的时候,我们会接触到Laravel的数据库迁移,也叫做Migrations,很多新手对于为什么要数据库迁移以及好处不是很了解,对此,这篇文章就给大家介绍一下Migrations。 什么是 Migrations? 我们先来看一下Laravel官方文档怎么写的: Migrations
在学习Laravel框架的时候,我们会接触到Laravel的数据库迁移,也叫做Migrations,很多新手对于为什么要数据库迁移以及好处不是很了解,对此,这篇文章就给大家介绍一下Migrations。 什么是 Migrations? 我们先来看一下Laravel官方文档怎么写的: Migrations are like version control for your database, allowing your team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you've faced the problem that database migrations solve. 简单概括起来,就是我们可以将Migrations看作一种数据库的VCS(Version Control System),即版本控制系统。可以通过Laravel的artisan命令快速创建、修改或还原数据库结构。 $ php artisan make:migration create_samples_table --create=samples 注意php artisan命令需要在项目根目录下运行。--create==samples这个选项表明我们想要建立一个名为samples的数据库表,所以artisan会自动在databasemigrations目录下建立一个叫2017_03_13_061422_create_samples_table.php的文件(其中前缀是创建该文件的日期和时间,用于区分迁移文件的时间先后顺序),并且会自动填充好Schema::create这个方法,方便我们创建更多的column: <?php use IlluminateSupportFacadesSchema; use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; class CreateSamplesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('samples', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('samples'); } } 我们看到,这个类中有up和down两个方法。up中我们需要添加创建数据表的函数,以及添加各个栏目的名称及属性。而down方法中我们需要添加在回滚该迁移文件时应该有什么样的结果(这里我们直接删除这张表)。 可以看出,up和down中的操作是对应的,在up中进行了什么操作,down中就需要撤销这些操作。现在我们详细来看一下up方法。我们看到,Schema::create这个方法是用来创建我们数据表的,在方法中,我们看到Laravel已经为我们填充了几个columns。 $table->increments('id')将创建一个名为id的column,并赋予PRIMARY KEY、UNSIGNED及AUTO INCREMENT属性。 $table->timestamps()将创建created_at和updated_at两个column(类型是DATETIME)。 注意:Laravel默认认为每个table都会存在一个id栏目,并且要求每个table都要有created_at和updated_at这两个栏目。 现在,我们要在samples表里增加一个名为name的VARCHAR类型的栏目,该怎么做呢?很简单,只需要加上这行: $table->string('name'); 现在问题来了,我们突然想在samples表里,添加一个名为url的栏目,该怎么做呢?我们分情况讨论。 1. 我们处于本地开发阶段,数据使用种子(Seed)文件进行填充。 对于本地开发,如果想省事,可以直接在samples表的迁移文件中,添加上我们需要的栏目: $table->string('url', 200)->nullable(); 然后我们重置数据库并做种: $ php artisan migrate:refresh --seed 这样就完成了。打开samples表,我们会发现新的栏目已经被创建。 注意,php artisan migrate:refresh命令相当于 $ php artisan migrate:reset (编辑:开发网_开封站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |