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?

More than 1 year has passed since last update.

[laravel phpunit] factoryで外部キーを設定する

Posted at

はじめに

外部キーのあるFactoryに対し、外部キーを設定し、リレーションする方法を調べてみました。

QuestionFactory
<?php

namespace Database\Factories;

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

class QuestionFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
                'question' => $this->faker->text(),
                'answer' => $this->faker->text(),
                'share' => false,
                'user_id' => function() {
                    return User::factory()->create()->id;
                },
            ];
    }
}
TestControllerTest

    public function setUp(): void
    {
        parent::setUp();
        //userFactory作成
        $this->user = User::factory()->create();
        //user_idを作成したuserFactoryのidで上書き
        $this->question = Question::factory()->create(['user_id' => $this->user->id]);
    }

参考

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?