【发布时间】:2021-04-25 09:46:41
【问题描述】:
在创建工厂和播种机时,我无法找到如何管理外键。
我有一个users 表和一个blog_posts 表。 blog_posts 表有一个引用 users.id 的外键 user_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
]);
}
【问题讨论】: