我需要在不同的语言与行DB种子.例如,我的模型Books具有字段titlecontentlanguage_id.和带有语言信息的型号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等)从种子传递到工厂?

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

推荐答案

您不能将区域设置代码从Seed传递到工厂,但如果要使工厂动态,则可以创建一个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();
    }
}

Php相关问答推荐

为什么注册SIGHUP的处理程序函数会阻止在PHP CLI中等待输入时点击X关闭Xterm窗口?""

PHP cUrl扩展与v8.2.12更新损坏

Laravel迁移返回SQL错误,但SQL有效且工作正常

未在moodle上运行的计划任务

在ShipStation for WooCommerce中使用自定义订单项目元数据

Htaccess-重写对&api.php";的API请求以及对";web.php";的其他请求

如何从Laravel中的Spatie\Dns\Records\A对象中提取IP地址

防止同时从Laravel中的用户帐户中提取

在 WooCommerce 中何时何地执行 woocommerce_order_status_completed_notification 挂钩?

单个产品页面 WooCommerce 订阅价格字符串的更改

后退按钮不起作用 laravel ajax crud

php/html OnSubmit 禁用输入类型提交未给出预期结果

PHP删除具有相同键的项目,除了具有最低值的项目

PHP preg_replace括号和方括号内的所有逗号

如何使用动态变量定义 bind_result?

我试图在我的视图上显示从数据库中获取的数据,但我无法显示它.拉维尔 10.x /

为什么在 phpunit 的开头测试 PHP_VERSION?

从 laravel 中的日期类型中删除时间

升级到 PHP 8.2:ksort 和 krsort 更改

如何将 2021-04-08T22:25:09.335541Z 作为时间戳保存到 Laravel 中的数据库中?