III. Tạo model
1. Tạo file model
- Dùng terminal, chạy từng lệnh sau:
1 2 3 |
php artisan make:model Category php artisan make:model Brand php artisan make:model Product |
- Vào trong app/.. đã thấy có 3 file php tương ứng
2. Định nghĩa từng Model
- Giả sử với file Product.php trong app/..
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Product extends Model { protected $table = 'product'; protected $fillable = ['product_name','product_desc','thumbnail', 'gallery','category_id','brand_id','price','quantity']; } |
3. Định nghĩa factory
- Vào /database/factories/UserFactory.php, thêm vào cuối như sau:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$factory->define(\App\Brand::class,function (Faker $faker){ return [ 'product_name' => $faker -> unique() ->name, 'product_desc' => $faker -> title, 'thumbnail' => $faker -> imageUrl(), 'gallery' => $faker -> imageUrl().",". $faker -> imageUrl(), 'price' => random_int(1,1000), 'quantity' => random_int(1,100), 'category_id' => random_int(1,100), 'brand_id' => random_int(1,100), ]; }); //ở trên nghĩa là lấy dữ liệu giả mạo (faker), lấy các tên "name" để làm tên cho 'product_name' |
4. Định nghĩa seeds
- Tạo file CategorySeeder.php trong seeds bằng terminal
1 |
php artisan make:seeder CategorySeeder |
- Định nghĩa file /database/seeds/CategorySeeder.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php use Illuminate\Database\Seeder; class CategorySeeder extends Seeder { public function run() { // factory(\App\Category::class,100)->create(); // factory(\App\Brand::class,100)->create(); factory(\App\Product::class,1000)->create(); // chạy dòng nào thì database sẽ add số lượng tương ứng với bảng đó, có thể chạy cả 3 cùng lúc } } |
- Định nghĩa file /database/seeds/DatabaseSeeder.php
1 2 3 4 5 6 7 8 9 10 11 |
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { public function run() { $this->call(CategorySeeder::class); } } |
5. Khởi chạy seeds
- Dùng terminal
1 |
php artisan db:seed |
- Khi đã tạo nhiều dữ liệu fake rồi, muốn refresh lại seed lại thì dùng lệnh sau:
1 |
php artisan migrate:refresh --seed |
- Quay lại database, trong bảng Category, đã tạo ra được 100 dữ liệu fake 😀