1
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?

Laravel Factoryで外部キー付きのテストデータを使用する

1
Posted at

Laravel Factoryで外部キー付きのテストデータを自動作成するには、has()メソッドとモデルリレーションを使います。これで親データを先に作成→子データに外部キー自動設定が可能です。

基本パターン:親子リレーション

例:bagsテーブル(user_idでUserを参照)

1. Userモデルにリレーション定義

// app/Models/User.php
class User extends Model
{
    public function bags()
    {
        return $this->hasMany(Bag::class);
    }
}

2. BagFactoryで外部キー自動解決

// database/factories/BagFactory.php
public function definition(): array
{
    return [
        'name' => fake()->sentence(),
        // user_idは明示的に書かなくてOK!
    ];
}

// 親子関係を自動作成
public function configure(): static
{
    return $this->state(fn (array $attributes) => [
        'user_id' => User::factory(),
    ]);
}

// または has() で簡潔に

3. テストで1行で親子作成

public function test_bag_with_user()
{
    // Userを自動作成し、そのIDをBagの外部キーに入れる
    $bag = Bag::factory()->create();
    
    // または明示的に複数作成
    $bags = User::factory()
        ->has(Bag::factory()->count(3))  // User1人にBag3件
        ->create();
        
    $this->assertCount(3, $bags[0]->bags);
}
1
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
1
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?