下面的代码是我的数据库播种器中使用的工厂。
问题是一些评论在一个帖子下,而另一些评论在另一个评论下。
话虽如此,我需要找到一种方法来为帖子或评论(而不是两者)生成foreign_id关系。
此外,最大的挑战是在某些情况下评论需要与另一个评论具有foreign_id关系。现在使用下面的代码,NULL 将始终出现在数据库列 comment_id 中...我想它不会确认该种子运行中新创建的记录...
请帮忙!
class CommentFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'user_id' => User::inRandomOrder()->first(), // Gets a random user ID
'post_id' => Post::inRandomOrder()->first(),
'comment_id' => Comment::inRandomOrder()->first(), // !!! THIS LINE HERE !!!
'content' => fake()->paragraph(2)
];
}
}
谢谢!
我尝试在 if 语句中使用 rand(0, 1) 来在帖子或其他评论下创建评论。
问题是,当在另一个评论下创建评论时,comment_id 的外部 id 始终为空,因为我的数据库在运行播种器时没有评论。
答案如下: 我必须利用 configure() 方法和 afterCreating() 方法
class CommentFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Comment::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'user_id' => User::inRandomOrder()->first()->id,
'content' => $this->faker->paragraph(2),
];
}
/**
* Configure the factory to create comments with appropriate relationships.
*
* @return $this
*/
public function configure()
{
return $this->afterCreating(function (Comment $comment) {
// Decide whether to attach the comment to a post or another comment
if (rand(0, 1) === 0) {
$post = Post::inRandomOrder()->first();
$comment->post_id = $post->id;
$comment->save();
} else {
// Attach the comment to another random comment
$parentComment = Comment::inRandomOrder()->first();
$comment->comment_id = $parentComment->id;
$comment->save();
}
});
}
}