php 我如何创建一个工厂,创建随机标题没有一个点在最后?

cu6pst1q  于 2024-01-05  发布在  PHP
关注(0)|答案(2)|浏览(180)

我正在做一个Laravel 8博客应用。我需要大量的文章来测试分页。
为此,我创建了这个工厂:

  1. class ArticleFactory extends Factory
  2. {
  3. /**
  4. * The name of the factory's corresponding model.
  5. *
  6. * @var string
  7. */
  8. protected $model = Article::class;
  9. /**
  10. * Define the model's default state.
  11. *
  12. * @return array
  13. */
  14. public function definition()
  15. {
  16. $title = $this->faker->sentence(2);
  17. return [
  18. 'user_id' => $this->faker->randomElement([1, 2]),
  19. 'category_id' => 1,
  20. 'title' => $title,
  21. 'slug' => Str::slug($title, '-'),
  22. 'short_description' => $this->faker->paragraph(1),
  23. 'content' => $this->faker->paragraph(5),
  24. 'featured' => 0,
  25. 'image' => 'default.jpg',
  26. ];
  27. }
  28. }

字符串
问题
不幸的是,articles表中的title列填充了结尾有一个点的句子。标题不应该以点结尾。

我该如何解决这个问题?

qoefvg9y

qoefvg9y1#

你可以用$this->faker->words(3, true);代替$this->faker->sentence(2);,在这里你可以用你想要的字数来替换3true在那里,所以它返回一个字符串,而不是一个数组。
它加了一个点,因为你使用了->sentence(),通常,句子的结尾有一个句号,而单词的结尾通常没有句号。
当然,您也可以使用rand()提供随机数量的单词。

h43kikqp

h43kikqp2#

这就是我选择实现预期结果的方式,以防它帮助其他人:

  1. public function definition() {
  2. $title = $this->faker->sentence(2);
  3. return [
  4. 'user_id' => $this->faker->randomElement([1, 2]),
  5. 'category_id' => 1,
  6. 'title' => rtrim($title, '.'),
  7. 'slug' => Str::slug($title, '-'),
  8. 'short_description' => $this->faker->paragraph(1),
  9. 'content' => $this->faker->paragraph(5),
  10. 'featured' => 0,
  11. 'image' => 'default.jpg',
  12. ];
  13. }

字符串

展开查看全部

相关问题