New*_* BB 7 php laravel eloquent laravel-factory
我无法找到在创建工厂和播种机时如何管理外键。
我有一张users桌子和一张blog_posts桌子。该blog_posts表有一个user_id引用 的外键users.id。我想在我的数据库中添加用户和博客文章。
我已经了解了如何使用以下内容为每个种子博客文章创建新用户:
/**
* Define the BlogPost model's default state.
*
* @return array
*/
public function definition()
{
return [
'user_id' => User::factory(),
'created_at' => now(),
'updated_at' => now(),
'title' => $this->faker->words(5, true),
'body' => $this->faker->paragraphs(6, true)
];
}
Run Code Online (Sandbox Code Playgroud)
...但我想引用现有用户,因为我正在像这样执行数据库种子:
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call([
UsersTableSeeder::class,
BlogPostsTableSeeder::class
]);
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*lli 12
我们可以检索一个随机的存在User并将其分配如下BlogPost Factory:
/**
* Define the BlogPost model's default state.
*
* @return array
*/
public function definition()
{
return [
'user_id' => User::inRandomOrder()->first()->id,
'created_at' => now(),
'updated_at' => now(),
'title' => $this->faker->words(5, true),
'body' => $this->faker->paragraphs(6, true)
];
}
Run Code Online (Sandbox Code Playgroud)
假设您的 User 模型具有hasMany名为 的关系blogPosts,您可以执行以下操作:
User::factory()
->hasBlogPosts(6)
->create();
Run Code Online (Sandbox Code Playgroud)
这将创建您的用户和 6 个关联的博客帖子。
| 归档时间: |
|
| 查看次数: |
4526 次 |
| 最近记录: |