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,
},
.............
'프로그래밍언어 > php' 카테고리의 다른 글
Laravel(artisan) 명령어 정리 (0) | 2023.09.17 |
---|---|
HTTP 상태코드 - 200, 201 , 301 , 400 , 401 ,404 , 500 , 503 (0) | 2023.09.03 |
[PHP] 특수문자 있는지 여부 확인 (0) | 2020.04.24 |
PHP 특수문자 제거 정규표현식 (0) | 2020.02.10 |
HTML파일안에서 PHP 내용이 주석처리되어 개발자도구에 표시됨 (1) | 2019.07.09 |