본문 바로가기

프로그래밍언어/php

PHP Laravel8 더미값 생성 (Model,Factory 생성) 예제

1. 테이블 스키마 생성 및 정의

php artisan make:migration CreateProductsTable

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id()->comment('상품id');
            $table->string('name',255)->comment('상품명');
            $table->bigInteger('price')->comment('상품금액');
            $table->foreignId('user_id')->constrained('users');
            $table->timestamps();
        });
    }
 php artisan migrate

2. factory와 Model 생성

php artisan make:model Product
php artisan make:factory ProductFactory --model Product

3. Product모델 수정



namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
    
    protected $table = 'products';

    protected $fillable = [
        'id','name', 'price','user_id','created_at','updated_at'
    ];



}

4. Product팩토리 수정



namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Product;

class ProductFactory extends Factory
{
    protected $model = Product::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name'=>$this->faker->name,
            'price'=>$this->faker->numberBetween(10,1000),
            'user_id'=>\App\Models\User::factory(),
            'created_at'=>now(),
            'updated_at'=>now(),
        ];
    }
}

5.더미값 생성

php artisan tinker

Product::factory()->count(20)->create()



[!] Aliasing 'Product' to 'App\Models\Product' for this Tinker session.
= Illuminate\Database\Eloquent\Collection {#6213
    all: [
      App\Models\Product {#7010
        name: "Kris Moore",
        price: 467,
        user_id: 17,
        created_at: "2023-09-20 16:13:04",
        updated_at: "2023-09-20 16:13:04",
        id: 2,
      },
      App\Models\Product {#6966
        name: "Miss Marie Luettgen Sr.",
        price: 804,
        user_id: 18,
        created_at: "2023-09-20 16:13:04",
        updated_at: "2023-09-20 16:13:04",
        id: 3,
      },
      App\Models\Product {#7224
        name: "Miss Sabryna Roberts",
        price: 347,
        user_id: 19,
        created_at: "2023-09-20 16:13:04",
        updated_at: "2023-09-20 16:13:04",
        id: 4,
      },
	  .............