[Bài đọc] Sử dụng Migration

Cơ sở dữ liệu

Migration được dùng để làm gì?

Migration được coi như là hệ thống quản lý phiên bản cho cơ sở dữ liệu, cho phép nhóm lập trình có thể dễ dàng thay đổi và chia sẻ schema (đối tượng mô tả cấu trúc của một bảng) của database với nhau. Migration cơ bản được sử dụng cùng với schema builder để dễ dàng xây dựng cấu trúc cho database schema. Khi đó những vấn đề như thêm cột vào bảng hay cập nhật tên bảng, migration sẽ xử lý vấn đề này dễ dàng.

Schema facade hỗ trợ việc tạo và thao tác trên các bảng mà không cần biết về database, tương ứng và mạch lạc khi giao tiếp với các hệ thống database khác nhau mà Laravel hỗ trợ.

Tạo migration

Để tạo một migration, sử dụng câu lệnh Artisan make:migration:

php artisan make:migration create_users_table

Câu lệnh trên tạo một migration có tên là create_users_table.

File migratioin được tạo ra trong thư mục  database/migrations .

Sử dụng tham số --create để tạo các migration với mục đích tạo mới một bảng:

php artisan make:migration create_users_table --create=users

Sử dụng tham số --table để tạo các migration để cập nhật một bảng:

php artisan make:migration add_votes_to_users_table --table=users

Cấu trúc của file migration

Một migration class chứa hai hàm cơ bản là: updown. Hàm up được dùng để tạo table, cột hay index mới hoặc thực hiện các công việc cập nhật bảng trong database, trong khi hàm down đơn giản chỉ dùng để làm ngược lại những thao tác ở hàm up.

Bên trong hai hàm này bạn có thể sử dụng schema builder để tạo và chỉnh sửa table rõ ràng hơn. Để tìm hiểu tất cả các hàm được cung cấp trong Schema builder. Ví dụ, hãy cùng nhau làm một ví dụ về migration bằng việc tạo ra một bảng tên là flights:

Ví dụ, đoạn mã sau đây được dùng để tạo bảng flights :

<?php

use Illuminate\Support\Facades\Schema;
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');
    }
}

Chạy migration

Để thực thi tất cả các migration trong chương trình, sử dụng lệnh Artisan migrate:

php artisan migrate

Các loại cột

Chúng ta có thể sử dụng các phương thức sau để tạo các cột tương ứng.

CommandDescription
$table->bigIncrements('id');Incrementing ID (primary key) using a “UNSIGNED 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->dateTimeTz('created_at');DATETIME (with timezone) 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', 8, 2);FLOAT equivalent for the database, 8 digits in total and 2 after the decimal point.
$table->increments('id');Incrementing ID (primary key) using a “UNSIGNED INTEGER” equivalent.
$table->integer('votes');INTEGER equivalent for the database.
$table->ipAddress('visitor');IP address 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->macAddress('device');MAC address equivalent for the database.
$table->mediumIncrements('id');Incrementing ID (primary key) using a “UNSIGNED MEDIUM INTEGER” equivalent.
$table->mediumInteger('numbers');MEDIUMINT equivalent for the database.
$table->mediumText('description');MEDIUMTEXT equivalent for the database.
$table->morphs('taggable');Adds unsigned INTEGER taggable_id and STRING taggable_type.
$table->nullableMorphs('taggable');Nullable versions of the morphs() columns.
$table->nullableTimestamps();Nullable versions of the timestamps() columns.
$table->rememberToken();Adds remember_token as VARCHAR(100) NULL.
$table->smallIncrements('id');Incrementing ID (primary key) using a “UNSIGNED SMALL INTEGER” equivalent.
$table->smallInteger('votes');SMALLINT equivalent for the database.
$table->softDeletes();Adds nullable 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->timeTz('sunrise');TIME (with timezone) equivalent for the database.
$table->tinyInteger('numbers');TINYINT equivalent for the database.
$table->timestamp('added_on');TIMESTAMP equivalent for the database.
$table->timestampTz('added_on');TIMESTAMP (with timezone) equivalent for the database.
$table->timestamps();Adds nullable created_at and updated_at columns.
$table->timestampsTz();Adds nullable created_at and updated_at (with timezone) columns.
$table->unsignedBigInteger('votes');Unsigned BIGINT equivalent for the database.
$table->unsignedInteger('votes');Unsigned INT equivalent for the database.
$table->unsignedMediumInteger('votes');Unsigned MEDIUMINT equivalent for the database.
$table->unsignedSmallInteger('votes');Unsigned SMALLINT equivalent for the database.
$table->unsignedTinyInteger('votes');Unsigned TINYINT equivalent for the database.
$table->uuid('id');UUID equivalent for the database.

Leave a Reply

Your email address will not be published.