我如何创建一个在末尾没有点的随机标题的工厂?

How do I make a factory that creates random titles without a dot at the end?

我正在开发 Laravel 8 博客应用程序 。我需要大量的文章来测试分页。

为此,我制作了这个工厂:

class ArticleFactory extends Factory
{ 
 /**
 * The name of the factory's corresponding model.
 *
 * @var string
 */
protected $model = Article::class;

/**
 * Define the model's default state.
 *
 * @return array
 */
public function definition()
{
    
    $title = $this->faker->sentence(2);

    return [
          'user_id' => $this->faker->randomElement([1, 2]),
          'category_id' => 1,
          'title' => $title,
          'slug' => Str::slug($title, '-'),
          'short_description' => $this->faker->paragraph(1),
          'content' => $this->faker->paragraph(5),
          'featured' => 0,
          'image' => 'default.jpg',
    ];
  }
}

问题

不幸的是,articles table 中的 title 列填充了末尾有一个点的句子。标题应该以点结尾。

我该如何解决这个问题?

您可以使用 $this->faker->words(3, true); 而不是 $this->faker->sentence(2);,您可以将 3 替换为您想要的字数。 true 在那里所以它 returns 一个字符串而不是一个数组

它添加了一个点,因为您使用 ->sentence() 并且句子通常在末尾有句号。而单词通常在末尾没有句号。

您当然也可以使用 rand() 提供随机数量的单词。假设您希望标题在 5 到 15 个单词之间,您可以使用 $this->faker->words(rand(5, 15), true);

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

public function definition() {
        
  $title = $this->faker->sentence(2);

  return [
    'user_id' => $this->faker->randomElement([1, 2]),
    'category_id' => 1,
    'title' => rtrim($title, '.'),
    'slug' => Str::slug($title, '-'),
    'short_description' => $this->faker->paragraph(1),
    'content' => $this->faker->paragraph(5),
    'featured' => 0,
    'image' => 'default.jpg',
   ];
}