php 将参数传递给laravel 9工厂

shyt4zoc  于 2022-12-17  发布在  PHP
关注(0)|答案(2)|浏览(111)

我需要用不同语言的行作为数据库的种子。例如,我有一个带有字段titlecontentlanguage_id的模型Books,还有一个带有语言信息的模型Languages

Schema::create('languages', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('code', 2);
    $table->timestamps();
});
Schema::create('books', function (Blueprint $table) {
    $table->id();
    $table->foreignId('language_id');
    $table->string('title');
    $table->text('content');
    $table->timestamps();

    $table->foreign('language_id')->references('id')->on('languages')->onUpdate('cascade')->onDelete('cascade');
});

我做了BookFactory

class BookFactory extends Factory
{
    public function definition()
    {
        return [
            'title' => fake()->sentence(rand(3, 7)),
            'content' => fake()->sentences(rand(5, 11))
        ];
    }
}

我可以将语言参数传递给fake()函数,例如fake('de_DE')。我如何将区域设置代码(de_DE等)从seed传递给工厂?

class DatabaseSeeder extends Seeder
{
    public function run()
    {   
        \App\Models\Book::factory(10)->create();
    }
}
jdzmm42g

jdzmm42g1#

不能将seed中的locale代码传递给factory,但如果希望使factory动态化,可以创建一个state()

class BookFactory extends Factory
{
    public function definition()
    {
        return [
            'title' => fake()->sentence(rand(3, 7)),
            'content' => fake()->sentences(rand(5, 11))
        ];
    }

    public function setLanguage(string $locale)
    {
        return $this->state(fn (array $attributes) => [
            'title' => fake($locale)->sentence(rand(3,7)),
            'content' => fake($locale)->realText(500), // you can use real text so that it will display a real text snippet.
        ])
    }
}

如果您想使用它:

class DatabaseSeeder extends Seeder
{
    public function run()
    {   
        \App\Models\Book::factory(10)->setLanguage('de_DE')->create();
    }
}
lbsnaicq

lbsnaicq2#

您可以使用下面的代码片段来解决这个问题Book::factory(10,[“locale”=〉1])-〉create();并使用states属性从工厂获取区域设置$this-〉states[1][“locale”]

  • )请参阅此文档https:laravel.com/docs/9.x/eloquent-factories#factory-states以了解实施情况

相关问题