gpt4 book ai didi

Laravel 8 个工厂

转载 作者:行者123 更新时间:2023-12-04 01:11:38 31 4
gpt4 key购买 nike

谁能告诉我如何用关系等建立工厂......

我有一个带有 2 个外键的 post 表:user_id 和 category_id我需要生成虚拟数据,但我不知道该怎么做。

我曾尝试先创建类别,然后对帖子和用户做一些事情,但没有成功。

后工厂:

public function definition()
{
$title = $this->faker->sentence;
$slug = Str::slug($title);
return [
'title' => $title,
'slug' => $slug,
'image' => $this->faker->imageUrl(900, 300),
'content' => $this->faker->text(300),
];
}

类别工厂:

public function definition()
{
$category = $this->faker->words(2, true);
$slug = Str::slug($category);
return [
'category' => $category,
'slug' => $slug
];
}

而用户工厂只是默认的:)

最佳答案

您可以检查您是否有足够的记录,并查询数据库以找到随机用户和类别以用于每个帖子。但是,如果没有足够的记录(20 个用户和 7 个类别),请创建一个新记录。

后工厂:

public function definition()
{
$title = $this->faker->sentence;
$slug = Str::slug($title);
$user = User::count() >= 20 ? User::inRandomOrder()->first()->id: User::factory();
$category = Category::count() >= 7 ? Category::inRandomOrder()->first()->id: Category::factory();

return [
'title' => $title,
'slug' => $slug,
'image' => $this->faker->imageUrl(900, 300),
'content' => $this->faker->text(300),
'user_id' => $user,
'category_id' => $category,
];
}

关于Laravel 8 个工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64624884/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com