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

cu6pst1q  于 5个月前  发布在  PHP
关注(0)|答案(2)|浏览(52)

我正在做一个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表中的title列填充了结尾有一个点的句子。标题不应该以点结尾。

我该如何解决这个问题?

qoefvg9y

qoefvg9y1#

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

h43kikqp

h43kikqp2#

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

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',
   ];
}

字符串

相关问题