1. BookingFactory 만들기
php artisan make:factory BookingFactory
2. 테이블
3. 팩토리 소스작성
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Booking;
use Carbon\Carbon;
use Faker\Generator as Faker;
$factory->define(Booking::class, function (Faker $faker) {
//한달전과 앞으로 한달 사이의 랜덤 날찌
$from = Carbon::instance($faker->dateTimeBetween('-1 months', '+1 months'));
//from 복제 후 random int로 0~14사이의 값을 랜던생성
$to = (clone $from)->addDays(random_int(0,14));
return [
'from' => $from,
'to' => $to
];
});
4. BookingsTableSeeder 만들기
php artisan make:seeder BookingsTableSeeder
5. 소스 작성
<?php
use App\Bookable;
use App\Booking;
use Illuminate\Database\Seeder;
class BookingsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Bookable::all()->each(function(Bookable $bookable){
$booking = factory(Booking::class)->make();
$bookings = collect([$booking]);
// 1~20의 예약 생성
for($i = 0; $i < random_int(1, 20); $i++){
$from = (clone $booking->to)->addDays(random_int(1,14));
$to = (clone $from)->addDays(random_int(0,14));
$booking = Booking::make([
'from' => $from,
'to' => $to
]);
$bookings->push($booking);
}
$bookable->bookings()->saveMany($bookings);
});
}
}
6. DatabaseSeeder.php 시더 추가
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call(BookablesTableSeeder::class);
$this->call(BookingsTableSeeder::class);
}
}
7. 마이그레이션 재실행
php artisan migrate:refresh --seed
8. 만들어진 데이터
'라라벨 > laravelbnb' 카테고리의 다른 글
30. 싱글액션컨트롤러만들기 (0) | 2020.03.05 |
---|---|
28. 예약 모델만들기 관계설정 (0) | 2020.03.04 |