Migrations trong CakePHP: Tạo bảng và sửa đổi bảng
Migrations: Tạo bảng và sửa đổi bảng bằng Migration
Migration là một tính năng mạnh mẽ trong CakePHP cho phép bạn quản lý cấu trúc cơ sở dữ liệu thông qua mã nguồn. Bạn có thể tạo, sửa đổi, hoặc xóa bảng mà không cần thao tác trực tiếp trên cơ sở dữ liệu.

1. Cài đặt Migrations Plugin
Để sử dụng Migration trong CakePHP, bạn cần cài đặt plugin Migrations:
composer require cakephp/migrations
Sau đó, tải plugin trong Application.php
:
// src/Application.php
$this->addPlugin('Migrations');
2. Tạo Migration mới
Lệnh tạo Migration
Sử dụng lệnh sau để tạo một Migration mới:
bin/cake bake migration CreateTableName
Ví dụ, nếu bạn muốn tạo một bảng articles
:
bin/cake bake migration CreateArticles
Sau khi chạy lệnh, một file Migration sẽ được tạo trong thư mục config/Migrations/
.
3. Định nghĩa bảng trong Migration
Mở file Migration vừa tạo (ví dụ: 20250119000000_CreateArticles.php
) và định nghĩa cấu trúc bảng.
Ví dụ:
use Migrations\AbstractMigration;
class CreateArticles extends AbstractMigration
{
public function change()
{
$table = $this->table('articles');
$table->addColumn('title', 'string', ['limit' => 255, 'null' => false])
->addColumn('body', 'text', ['null' => false])
->addColumn('created', 'datetime', ['default' => 'CURRENT_TIMESTAMP'])
->addColumn('modified', 'datetime', ['default' => 'CURRENT_TIMESTAMP', 'update' => 'CURRENT_TIMESTAMP'])
->create();
}
}
Các phương thức thường dùng:
- addColumn(): Thêm cột mới.
- removeColumn(): Xóa cột.
- renameColumn(): Đổi tên cột.
- addIndex(): Thêm chỉ mục (index).
- removeIndex(): Xóa chỉ mục.
- create(): Tạo bảng.
4. Chạy Migration
Sau khi định nghĩa cấu trúc bảng, bạn chạy Migration bằng lệnh:
bin/cake migrations migrate
Lệnh này sẽ áp dụng các thay đổi lên cơ sở dữ liệu.
5. Sửa đổi bảng bằng Migration
Để sửa đổi bảng hiện có, bạn tạo một Migration mới với tên mô tả thay đổi:
bin/cake bake migration AddColumnToArticles
Ví dụ: Thêm cột vào bảng articles
Trong file Migration mới tạo (ví dụ: 20250119000001_AddColumnToArticles.php
), thêm mã:
use Migrations\AbstractMigration;
class AddColumnToArticles extends AbstractMigration
{
public function change()
{
$table = $this->table('articles');
$table->addColumn('author', 'string', ['limit' => 100, 'null' => true])
->update();
}
}
Chạy lệnh để áp dụng thay đổi:
bin/cake migrations migrate
6. Một số thay đổi phổ biến
a. Xóa cột
$table = $this->table('articles');
$table->removeColumn('author')
->update();
b. Đổi tên cột
$table = $this->table('articles');
$table->renameColumn('title', 'headline')
->update();
c. Thêm chỉ mục (index)
$table = $this->table('articles');
$table->addIndex(['title'], ['unique' => true, 'name' => 'idx_title'])
->update();
d. Xóa bảng
$this->table('articles')->drop()->save();
7. Kiểm tra trạng thái Migration
Bạn có thể kiểm tra trạng thái các Migration đã áp dụng bằng lệnh:
bin/cake migrations status
Kết quả sẽ hiển thị danh sách các Migration đã chạy hoặc chưa chạy.
8. Hoàn tác Migration (Rollback)
Nếu muốn hoàn tác một Migration, bạn sử dụng lệnh:
bin/cake migrations rollback
Hoặc hoàn tác tất cả Migration:
bin/cake migrations rollback -t 0
9. Ví dụ thực tế
Tạo bảng users
bin/cake bake migration CreateUsers
File Migration:
use Migrations\AbstractMigration;
class CreateUsers extends AbstractMigration
{
public function change()
{
$table = $this->table('users');
$table->addColumn('username', 'string', ['limit' => 50, 'null' => false])
->addColumn('email', 'string', ['limit' => 100, 'null' => false])
->addColumn('password', 'string', ['null' => false])
->addColumn('created', 'datetime', ['default' => 'CURRENT_TIMESTAMP'])
->addColumn('modified', 'datetime', ['default' => 'CURRENT_TIMESTAMP', 'update' => 'CURRENT_TIMESTAMP'])
->create();
}
}
Chạy Migration:
bin/cake migrations migrate
Thêm cột role
vào bảng users
bin/cake bake migration AddRoleToUsers
File Migration:
use Migrations\AbstractMigration;
class AddRoleToUsers extends AbstractMigration
{
public function change()
{
$table = $this->table('users');
$table->addColumn('role', 'string', ['limit' => 20, 'null' => true])
->update();
}
}
Chạy Migration:
bin/cake migrations migrate
Kết luận
- Migrations giúp quản lý cơ sở dữ liệu dễ dàng và an toàn.
- Bạn có thể tạo bảng, sửa đổi bảng hoặc hoàn tác thay đổi chỉ bằng các lệnh đơn giản.
- Kết hợp với hệ thống kiểm soát phiên bản (Git), Migration là công cụ mạnh mẽ cho các dự án lớn.

Với hơn 10 năm kinh nghiệm lập trình web và từng làm việc với nhiều framework, ngôn ngữ như PHP, JavaScript, React, jQuery, CSS, HTML, CakePHP, Laravel..., tôi hy vọng những kiến thức được chia sẻ tại đây sẽ hữu ích và thiết thực cho các bạn.
Xem thêm

Chào, tôi là Vũ. Đây là blog hướng dẫn lập trình của tôi.
Liên hệ công việc qua email dưới đây.
lhvuctu@gmail.com