Hướng dẫn database seed cakephp 4

  • August 30, 2022
  • 701

Ở bài trước chúng ta đã tạo được database bằng cách sử dụng migration database Bài viết tiếp theo chúng ta sẽ tìm cách tạo dữ liệu mẫu cho database. Cakephp đã hỗ trợ sẵn hết rồi, bạn chỉ việc sử dụng database seed cakephp 4 là xong.

Create database seed cakephp

Cakephp đã hỗ trợ sẵn CLI command để tạo file seed, các file seed sẽ được tạo trong thư mục config/Seeds

Bây giờ chúng ta cùng tạo thử dữ liệu cho bảng admins, tạo file seed với command:


bin/cake bake seed Admins

file AdminsSeed.php sẽ được tạo trong thư mục config/Seeds, thêm logic tạo dữ liệu vào file, mình sẽ tạo 1 admin với username: huunv, password: 12345678


<?php
declare(strict_types=1);

use Cake\Auth\DefaultPasswordHasher;
use Cake\I18n\FrozenTime;
use Migrations\AbstractSeed;

/**
 * Admins seed.
 */
class AdminsSeed extends AbstractSeed
{
    /**
     * Run Method.
     *
     * Write your database seeder using this method.
     *
     * More information on writing seeds is available here:
     * https://book.cakephp.org/phinx/0/en/seeding.html
     *
     * @return void
     */
    public function run()
    {
        $connection = \Cake\Datasource\ConnectionManager::get('default')->newQuery();
        $count = $connection->select('id')->from('admins')->execute()->count();
        if (!$count) {
            $datetime = (new FrozenTime())->format('Y-m-d H:m:s');
            $data = [
                [
                    'username' => 'huunv',
                    'email' => 'nguyenhuu140490@gmail.com',
                    'password' => (new DefaultPasswordHasher())->hash('12345678'),
                    'last_login_datetime' => $datetime,
                    'status' => 1,
                    'created' => $datetime,
                    'modified' => $datetime,
                ],
            ];

            $table = $this->table('admins');
            $table->insert($data)->save();
        }
    }
}

Run seeding database

Giờ chúng ta sẽ tạo dữ liệu cho bảng admins, sử dụng CLI command


// Chạy tất cả các file seed
bin/cake migrations seed

// Chạy 1 file seed
bin/cake migrations seed --seed AdminsSeed

// Kết quả chạy thành công
 == AdminsSeed: seeding
 == AdminsSeed: seeded 0.0963s

Ngoài ra, cũng có thể call 1 seed từ seed khác


use Migrations\AbstractSeed;

class DatabaseSeed extends AbstractSeed
{
    public function run()
    {
        $this->call('AnotherSeed');
        $this->call('YetAnotherSeed');

        // You can use the plugin dot syntax to call seeders from a plugin
        $this->call('PluginName.FromPluginSeed');
    }
}

Như vậy là chúng ta đã tạo dữ liệu thành công cho bảng admins, các bảng khác cũng làm tương tự như trên. Chúc các bạn tạo dữ liệu thành công!