Laravel5.1学习笔记17 数据库3 数据迁移

Introduction

Migrations are like version control for your database, allowing a 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.

The Laravel Schema facade provides database agnostic support for creating and manipulating tables. It shares the same expressive, fluent API across all of Laravel‘s supported database systems.

Generating Migrations

To create a migration, use the make:migration Artisan command:

php artisan make:migration create_users_table

The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.

The --table and --create options may also be used to indicate the name of the table and whether the migration will be creating a new table. These options simply pre-fill the generated migration stub file with the specified table:

php artisan make:migration add_votes_to_users_table --table=users

php artisan make:migration create_users_table --create=users

Migration Structure

A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should simply reverse the operations performed by the upmethod.

Within both of these methods you may use the Laravel schema builder to expressively create and modify tables. To learn about all of the methods available on the Schema builder, check out its documentation. For example, let‘s look at a sample migration that creates a flights table:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFlightsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(‘flights‘, function (Blueprint $table) {
            $table->increments(‘id‘);
            $table->string(‘name‘);
            $table->string(‘airline‘);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop(‘flights‘);
    }
}

Running Migrations

To run all outstanding migrations for your application, use the migrate Artisan command. If you are using theHomestead virtual machine, you should run this command from within your VM:

php artisan migrate

If you receive a "class not found" error when running migrations, try running the composer dump-autoload command and re-issuing the migrate command.

Forcing Migrations To Run In Production

Some migration operations are destructive, meaning they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before these commands are executed. To force the commands to run without a prompt, use the --force flag:

php artisan migrate --force

Rolling Back Migrations

To rollback the latest migration "operation", you may use the rollback command. Note that this rolls back the last "batch" of migrations that ran, which may include multiple migration files:

php artisan migrate:rollback

The migrate:reset command will roll back all of your application‘s migrations:

php artisan migrate:reset
Rollback / Migrate In Single Command

The migrate:refresh command will first roll back all of your database migrations, and then run the migrate command. This command effectively re-creates your entire database:

php artisan migrate:refresh

php artisan migrate:refresh --seed

Writing Migrations

Creating Tables

To create a new database table, use the create method on the Schema facade. The create method accepts two arguments. The first is the name of the table, while the second is a Closure which receives a Blueprint object used to define the new table:

Schema::create(‘users‘, function ($table) {
    $table->increments(‘id‘);
});

Of course, when creating the table, you may use any of the schema builder‘s column methods to define the table‘s columns.

Checking For Table / Column Existence

You may easily check for the existence of a table or column using the hasTable and hasColumn methods:

if (Schema::hasTable(‘users‘)) {
    //
}

if (Schema::hasColumn(‘users‘, ‘email‘)) {
    //
}
Connection & Storage Engine

If you want to perform a schema operation on a database connection that is not your default connection, use theconnection method:

Schema::connection(‘foo‘)->create(‘users‘, function ($table) {
    $table->increments(‘id‘);
});

To set the storage engine for a table, set the engine property on the schema builder:

Schema::create(‘users‘, function ($table) {
    $table->engine = ‘InnoDB‘;

    $table->increments(‘id‘);
});

Renaming / Dropping Tables

To rename an existing database table, use the rename method:

Schema::rename($from, $to);

To drop an existing table, you may use the drop or dropIfExists methods:

Schema::drop(‘users‘);

Schema::dropIfExists(‘users‘);

Creating Columns

To update an existing table, we will use the table method on the Schema facade. Like the create method, the tablemethod accepts two arguments: the name of the table and a Closure that receives a Blueprint instance we can use to add columns to the table:

Schema::table(‘users‘, function ($table) {
    $table->string(‘email‘);
});
Available Column Types

Of course, the schema builder contains a variety of column types that you may use when building your tables:

Command

Description

$table->bigIncrements(‘id‘);

Incrementing ID using a "big integer" equivalent.

$table->bigInteger(‘votes‘);

BIGINT equivalent for the database.

$table->binary(‘data‘);

BLOB equivalent for the database.

$table->boolean(‘confirmed‘);

BOOLEAN equivalent for the database.

$table->char(‘name‘, 4);

CHAR equivalent with a length.

$table->date(‘created_at‘);

DATE equivalent for the database.

$table->dateTime(‘created_at‘);

DATETIME equivalent for the database.

$table->decimal(‘amount‘, 5, 2);

DECIMAL equivalent with a precision and scale.

$table->double(‘column‘, 15, 8);

DOUBLE equivalent with precision, 15 digits in total and 8 after the decimal point.

$table->enum(‘choices‘, [‘foo‘, ‘bar‘]);

ENUM equivalent for the database.

$table->float(‘amount‘);

FLOAT equivalent for the database.

$table->increments(‘id‘);

Incrementing ID for the database (primary key).

$table->integer(‘votes‘);

INTEGER equivalent for the database.

$table->json(‘options‘);

JSON equivalent for the database.

$table->jsonb(‘options‘);

JSONB equivalent for the database.

$table->longText(‘description‘);

LONGTEXT equivalent for the database.

$table->mediumInteger(‘numbers‘);

MEDIUMINT equivalent for the database.

$table->mediumText(‘description‘);

MEDIUMTEXT equivalent for the database.

$table->morphs(‘taggable‘);

Adds INTEGER taggable_id and STRING taggable_type.

$table->nullableTimestamps();

Same as timestamps(), except allows NULLs.

$table->rememberToken();

Adds remember_token as VARCHAR(100) NULL.

$table->smallInteger(‘votes‘);

SMALLINT equivalent for the database.

$table->softDeletes();

Adds deleted_at column for soft deletes.

$table->string(‘email‘);

VARCHAR equivalent column.

$table->string(‘name‘, 100);

VARCHAR equivalent with a length.

$table->text(‘description‘);

TEXT equivalent for the database.

$table->time(‘sunrise‘);

TIME equivalent for the database.

$table->tinyInteger(‘numbers‘);

TINYINT equivalent for the database.

$table->timestamp(‘added_on‘);

TIMESTAMP equivalent for the database.

$table->timestamps();

Adds created_at and updated_at columns.

Column Modifiers

In addition to the column types listed above, there are several other column "modifiers" which you may use while adding the column. For example, to make the column "nullable", you may use the nullable method:

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

Below is a list of all the available column modifiers. This list does not include the index modifiers:

Modifier

Description

->first()

Place the column "first" in the table (MySQL Only)

->after(‘column‘)

Place the column "after" another column (MySQL Only)

->nullable()

Allow NULL values to be inserted into the column

->default($value)

Specify a "default" value for the column

->unsigned()

Set integer columns to UNSIGNED

Modifying Columns
Prerequisites

Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column.

Updating Column Attributes

The change method allows you to modify an existing column to a new type, or modify the column‘s attributes. For example, you may wish to increase the size of a string column. To see the change method in action, let‘s increase the size of the name column from 25 to 50:

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

We could also modify a column to be nullable:

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

Renaming Columns

To rename a column, you may use the renameColumn method on the Schema builder. Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file:

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

Note: Renaming columns in a table with a enum column is not currently supported.

Dropping Columns

To drop a column, use the dropColumn method on the Schema builder:

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

You may drop multiple columns from a table by passing an array of column names to the dropColumn method:

Schema::table(‘users‘, function ($table) {
    $table->dropColumn([‘votes‘, ‘avatar‘, ‘location‘]);
});

Note: Before dropping columns from a SQLite database, you will need to add the doctrine/dbal dependency to your composer.json file and run the composer update command in your terminal to install the library.

Creating Indexes

The schema builder supports several types of indexes. First, let‘s look at an example that specifies a column‘s values should be unique. To create the index, we can simply chain the unique method onto the column definition:

$table->string(‘email‘)->unique();

Alternatively, you may create the index after defining the column. For example:

$table->unique(‘email‘);

You may even pass an array of columns to an index method to create a compound index:

$table->index([‘account_id‘, ‘created_at‘]);
Available Index Types

Command

Description

$table->primary(‘id‘);

Add a primary key.

$table->primary([‘first‘, ‘last‘]);

Add composite keys.

$table->unique(‘email‘);

Add a unique index.

$table->index(‘state‘);

Add a basic index.

Dropping Indexes

To drop an index, you must specify the index‘s name. By default, Laravel automatically assigns a reasonable name to the indexes. Simply concatenate the table name, the names of the column in the index, and the index type. Here are some examples:

Command

Description

$table->dropPrimary(‘users_id_primary‘);

Drop a primary key from the "users" table.

$table->dropUnique(‘users_email_unique‘);

Drop a unique index from the "users" table.

$table->dropIndex(‘geo_state_index‘);

Drop a basic index from the "geo" table.

Foreign Key Constraints

Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let‘s define a user_id column on the posts table that references the id column on ausers table:

Schema::table(‘posts‘, function ($table) {
    $table->integer(‘user_id‘)->unsigned();

    $table->foreign(‘user_id‘)->references(‘id‘)->on(‘users‘);
});

You may also specify the desired action for the "on delete" and "on update" properties of the constraint:

$table->foreign(‘user_id‘)
      ->references(‘id‘)->on(‘users‘)
      ->onDelete(‘cascade‘);

To drop a foreign key, you may use the dropForeign method. Foreign key constraints use the same naming convention as indexes. So, we will concatenate the table name and the columns in the constraint then suffix the name with "_foreign":

$table->dropForeign(‘posts_user_id_foreign‘);
时间: 2024-10-17 23:56:43

Laravel5.1学习笔记17 数据库3 数据迁移的相关文章

Laravel5.1学习笔记18 数据库4 数据填充

Introduction Writing Seeders Using Model Factories Calling Additional Seeders Running Seeders Introduction Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in database/seeds. See

Laravel5.1学习笔记15 数据库1 数据库使用入门

Introduction Running Raw SQL Queries Listening For Query Events Database Transactions Using Multiple Database Connections Introduction Laravel makes connecting with databases and running queries extremely simple across a variety of database back-ends

Laravel5.1学习笔记16 数据库2 查询构造器

Introduction Retrieving Results Aggregates Selects Joins Unions Where Clauses Advanced Where Clauses Ordering, Grouping, Limit, & Offset Inserts Updates Deletes Pessimistic Locking Introduction The database query builder provides a convenient, fluent

C++学习笔记17,构造函数体内初始化数据成员与构造函数初始化器的区别(一)

在构造体内初始化数据成员是最常见的方法. 例如: #include <iostream> using namespace std; class A { private: int i; string s; public: A(int ii,string ss){ //在构造函数体内初始化数据成员 i=ii; s=ss; cout<<"ctor:i="<<i<<",s="<<s<<endl; } /

Oracle 学习笔记 17 -- 异常处理(PL/SQL)

程序在执行过程中出现异常是正常的,在程序的编写过程中出现异常也是不可避免的.但是要有相应的异常处理的机 制,来保证程序的正常执行.PL/SQL程序执行过程中出现的错误,称为异常.一个优秀的程序都应该能够正确处理 各种出错的情况,并尽可能的从错误中恢复.PL/SQL提供了异常处理机制. 概念: 异常处理(exception)是用来处理正常执行过程中未预料的事件,程序块的异常处理定义的错误和自定义的错误, 由于PL/SQL程序块一旦产生异常而没有指出如何处理时,程序就会异常的终止. 有三种类型的错误

Symfony2学习笔记之数据库操作

数据库和Doctrine让我们来面对这个对于任何应用程序来说最为普遍最具挑战性的任务,从数据库中读取和持久化数据信息.幸运的是,Symfony和Doctrine进行了集成,Doctrine类库全部目标就是给你一个强大的工具,让你的工作更加容易. Doctrine是完全解耦与Symfony的,所以并不一定要使用它. 一个简单例子:一个产品,我们首先来配置数据库,创建一个Product对象,持久化它到数据库并把它读回来. 首先我们需要创建一个bundle: $php app/console gene

Python学习笔记_Chapter 6定制数据对象

1. 有用的BIF a. 判断字符串中是否包含子字符串 1 if s_a in s_b: b. pop() 描述:从指定的列表位置删除并返回一个数据项. 1 (sarah_name,sarah_dob)=l_rah.pop(0),l_rah.pop(0) 2 #pop(0)中0位置为list中第一个数据项 3 #第一次执行pop赋值给sarah_name c. strip() 输入的是字符串,返回的是列表 d.open 读文件时可以多种方式打开文件,取出的数据是不同的,可以是文本也可以是二进制.

学习Angularjs向数据库添加数据

今天学习angularjs向数据库添加数据. 学习此篇,得从以往几篇开始,因为那还有创建数据表等演示. 现在来创建一个添加的存储过程: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[usp_Goods_Insert] ( @Item NVARCHAR(55), @Description NVARCHAR(20), @Qty DECIMAL(10,2) ) AS IF EXISTS(SELECT T

Sharepoint2013搜索学习笔记之设置业务数据内容源(六)

Sharepoint搜索爬网组件支持爬Business Data Connectivity Service 承载的外部数据,关于Business Data Connectivity Service设置外部数据源,详请请参考:如何:在 SharePoint 2013 中为 SQL Server 创建外部内容类型,爬网设置步骤如下: 第一步,进入管理中心,点击管理应用程序,点击search service 应用程序进入到搜索管理配置页面,点击内容源 第二步,点击新建内容源,给内容源命名,在爬网内容类