0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CakePHP4 Fakerライブラリーを使って複数ダミーデータを作成

0
Last updated at Posted at 2021-07-19

Every Qiita #17
のんびり独学初学者の毎日投稿チャレンジ 17日目
今回は・・・
cakephp4で初期データをランダム生成した際の備忘録です。

データを複数保存したい

userデータを50程生成したいが、1つずつinsertするのは流石に面倒・・・
ランダムでデータを生成してくれるライブラリーがあれば使ってみたいと思った。

Fakerライブラリーのインストール

composerからFakerをインストールします。
$ composer require fzaninotto/faker
これで準備完了!あとは通常通りseedファイルを作成してFakerオブジェクトから任意のランダムデータを生成します。

seedファイルの生成

bin/cake bake seed Users
まずはusersテーブルのseedファイルをbakeします。

UsersSeed.php
 public function run()
 {
    $faker = Faker\Factory::create();
    $data = [];
    for($i=0; $i < 50; $i++){
        $data[] = [
            'email' => $faker->email,
            'password' => sha1($faker->password)
        ];
    }

    $table = $this->table('users');
    $table->insert($data)->save();
 }
  1. $faker = Faker\Factory::create()Fakerオブジェクトを変数に格納
  2. $faker->任意でランダムデータを生成します。
    sha1()でパスワードをハッシュ化します

seedファイルの実行

bin/cake migrations seed
これでダミーデータが保存されます。

Fakerメソッドの種類

名前や電話番号、住所など様々なものがありますので、上記から用途に合わせて使用してみてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?