LoginSignup
1
1

More than 3 years have passed since last update.

[Laravel]リレーション先のデータもファクトリでまとめて作成

Posted at

概要

テストを実装している時に一対一、または一対多のテーブルの情報があり、リレーション先のデータごとまとめてFactoryで作成したい時の方法をメモします。

例えば特定のUserと紐づいたPostを作成したいときなどに使えます。

ここではファクトリでのテストデータ作成方法には触れません。

環境

Laravel v8.12

実装

一対多テーブル
User→一
Post→多

Userからアクセス

Test.php
$user = User::factory()->has(Post::factory())->create();

Postの数を指定することもできます。

Test.php
$user = User::factory()->has(Post::factory()->count(3))->create();

Postからアクセス

$posts = Post::factory()->count(3)
    ->for(User::factory()->state([
        'name' => 'hogehoge',
    ]))

参考文献

公式

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