我找不到如何在创建工厂和填充器时管理外键的方法。
我有一个 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)
];
}
...但是我想引用现有的用户,因为我正在执行数据库种子操作,就像这样:
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call([
UsersTableSeeder::class,
BlogPostsTableSeeder::class
]);
}