Migrations trong Laravel

Chúng ta đã được học cách truy xuất database (cơ sở dữ liệu)  trong Laravel với Query Buider và Eloquent ORM rồi phải không nào. Thế nhưng hôm nay chúng ta sẽ học thêm 1 cách nữa để có thể thao tác dễ dàng hơn với cơ sở dữ liệu đó là sử dụng Migrations. Vậy Migrations trong Laravel là gì nó có tác dụng như thế nào chúng ta cùng theo dõi ngay dưới bài viết sau đây nhé các bạn!

1. Migrations trong Laravel là gì?

Migration trong Laravel giống như một control database có tác dụng quản lý cũng như lưu trữ lại cấu trúc của database giúp cho việc sửa đổi database trở lên dễ dàng hơn.

Điều kiện để sử dụng Migations:

  • Phải có kết nối với database. Nếu chưa biết cách kết nối với database xem lại Kết nối database Laravel
  • Migrations muốn sử dụng được thì phải nằm trong thư mục App/database/migrations

2. Tạo migrations.

Laravel cũng cung cấp chọ người dùng 2 cách để tạo Migrations đó là dùng tay và dùng lệnh, thế nhưng mình khuyến khích mọi người dùng lệnh.

Tạo Migrations bằng lệnh thì các bạn mở cmder lên và trỏ tới thư mục chứa project của mình như mọi khi và gõ 1 trong các lệnh sau tùy theo mục đích của bạn.

  • php artisan make:migration TenMigrate  : Tạo migrations thông thường.
  • php artisan make:migration TenMigrate --create=TableName  : Tạo migrations để tạo bảng mới
  • php artisan make:migration TenMigrate --table=TableName  : Tạo migrations chỉnh sửa bảng.

Trong đó :TenMigrate và TableName là các thông số các bạn có thể tùy chỉnh.

Ví Dụ: Ở bài Mình sẽ tạo Migrations create_tintuc_table để tạo table tintuc.

php artisan make:migration create_tintuc_table --create=tintuc

Nếu tạo thành công nó sẽ báo dạng như sau: Created migration: xxxxx: 


Lúc này bạn có thể kiểm tra lại bằng cách truy cập vào  App\database\migrations nếu thấy  có file tên trùng với phần xxxxx ở trên thì là đã thành công.


Tiếp đó các bạn mở file ra và sẽ thấy nội dung có dạng:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;


class CreateTintucTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tintuc', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tintuc');
    }
}

Giải thích cấu trúc

  • use Illuminate\Support\Facades\Schema; 
  • use Illuminate\Database\Schema\Blueprint; 
  • use Illuminate\Database\Migrations\Migration; 

Là các khai báo sử dụng cần cho thao tác Migration

Chúng ta cần quan tâm là 2 function up() và down():

  • public function up() dùng để thêm, bớt, thay đổi, ... nội dung bảng cơ sở dữ liệu - để thực thi ta cần sử dụng lệnh php artisan migrate
  • public function down() dùng phục hồi hay xóa bảng, ... - để thực thi ta cần sử dụng lệnh php artisan migrate:rollback

Với nội dung trên, ta đã có thể tạo bảng news với 1 cột là id, để có thể nhiều cột hơn ta thêm trực tiếp vào bên trong function up():

<?php


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


class CreateTintucTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tintuc', function (Blueprint $table) {
            $table->increments('id');
            $table->string('headline');
            $table->string('email');
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tintuc');
    }
}

3. Thực thi Migrations.

Tạo migrations xong dĩ nhiên cơ sở dữ liệu chưa có gì đâu chúng ta phải chạy migration bằng lệnh dưới đây trước

php artisan migrate

Nếu tạo bảng thành công quay lại database chúng ta sẽ thấy bảng mình vừa mới tạo. 

Như ở ví dụ trên chúng ta sẽ thấy bảng tintuc xuất hiện

Sau khi đã tạo và viết code cho migrate thì chúng ta cần phải chạy nó theo các cú pháp dưới đây. Ô sao lại có tận 4 bảng nhỉ hihi đừng lo vì các bảng còn lại là mặc định có sẵn khi bật migration rồi các bạn ạ

  • migrations: chứa dữ liệu của Migration, lưu trữ thông tin các bảng dữ liệu được tạo trong Migration.
  • tintuc: đây là bảng chúng ta đã tạo.
  • password_resets: bảng reset password có sẵn trong thư mục /database/migrations/, đây là table tồn tại sẵn của Laravel
  • users: bảng user có sẵn trong thư mục /database/migrations/, đây là table tồn tại sẵn của Laravel

Ngoài ra còn có các lệnh thực thi migrations khác:

php artisan migrate   Chạy migration
php artisan migrate:fresh
Drop tất cả các bảng trong database và chạy lại migrate:
php artisan migrate:install
Cài đặt migration
php artisan migrate:refreshRollback toàn bộ các migrations của bạn và thực hiện migrate lại.
php artisan migrate:reset
Reset lại migration
php artisan migrate:rollback
Để khôi phục lại lần thực hiện migration gần nhất
php artisan migrate:statusXem trạng thái của migration



4. Các cú pháp khác trong Migrations.

Dưới đây là một số các câu lệnh tạo bảng hay dùng trong Migrations.

LệnhChức năng
$table->bigIncrements('id');Tạo cột id khóa chính tự động tăng kiểu bigint
$table->bigInteger('votes');Tạo cột votes với kiểu bigint
$table->binary('data');Tạo cột data với kiểu blob
$table->boolean('confirmed');Tạo cột confirmed với kiểu boolean
$table->char('name', 4);Tạo cột name với kiểu char tối đa 4 kí tự
$table->date('created_at');Tạo cột created_atvới kiểu date
$table->dateTime('created_at');Tạo cột created_atvới kiểu dateTime
$table->dateTimeTz('created_at');Tạo cột name với kiểu DATETIME (with timezone)
$table->decimal('amount', 5, 2);Tạo cột name với kiểu DECIMAL
$table->double('column', 15, 8);Tạo cột name với kiểu DOUBLE
$table->enum('choices', ['foo', 'bar']);ENUM tương đương cho cơ sở dữ liệu.
$table->float('amount', 8, 2);FLOAT tương đương cho cơ sở dữ liệu, 8 chữ số trong tổng số và 2 sau dấu thập phân.
$table->increments('id');ID tăng dần (khóa chính) bằng cách sử dụng "UNSIGNED INTEGER" tương đương.
$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->nullableTimestamps();Same as timestamps().
$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.


5. Xử lý lỗi khi chạy lệnh Migration

Nếu gặp lỗi sau khi chạy lệnh php artisan migrate thì nguyên nhân có thể là phiên bản MySQL của bạn thấp hơn yêu cầu hãy nâng cấp nó hoặc vào database xóa những bảng đã tồn tại để tránh lỗi bảng đã tồn tại.

6. Lời kết.

Trên đây là những kiến thức cơ bản về Migrations trong Laravel, muốn tìm hiểu chi tiết hơn các bạn có thể theo dõi documention của Laravel nhé. Cảm ơn các bạn đã theo dõi.Kết nối database Laravel

Bình luận