2

尝试在 laravel 8 中运行工厂时出现此错误。我查看了几篇关于此错误的帖子,但它们似乎都来自直接错误地保存/创建。不使用工厂。所以我不确定为什么工厂没有正确保存它。

我的迁移有:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('slug');
        $table->string('name');
        $table->longText('desc');
        $table->foreignId('user_id')->constrained();
        $table->timestamps();
        $table->softDeletes();
    });
}

我的模型有:

class Post extends Model
{
    use HasFactory, SoftDeletes;

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function setSlugAttribute($value)
    {
        $this->attributes['slug'] = Str::slug($this->name);
    }
}

我的工厂有:

public function definition()
{
    return [
        'name' => $this->faker->words,
        'desc' => $this->faker->sentence,
        'user_id' => rand(1,10)
    ];
}

我的帖子播种机有:

public function run()
{
    Post::factory()->times(13)->create();
}

我的主 DatabaseSeeder 运行一个用户播种器,可以播种 10 个用户。然后是一个播种机来播种 13 个帖子。

我运行php artisan migrate:fresh --seed,当它到达 Post Seeder 并出现以下错误时失败:

类型错误

传递给 Illuminate\Database\Grammar::parameterize() 的参数 1 必须是数组类型,给定字符串,在 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar 中调用.php 在第 886 行

在 vendor/laravel/framework/src/Illuminate/Database/Grammar.php:136 132▕ * 133▕ * @param array $values 134▕ * @return string 135▕ */ ➜ 136▕ public function parameterize(array $values) 137▕ { 138▕ return implode(', ', array_map([$this, 'parameter'], $values)); 139▕}140▕</p>

  +1 vendor frames    2   [internal]:0
  Illuminate\Database\Query\Grammars\Grammar::Illuminate\Database\Query\Grammars\{closure}("Odio

voluptatem quis facere possimus ut.", "desc")

  +13 vendor frames    16  database/seeders/PostsSeeder.php:17
  Illuminate\Database\Eloquent\Factories\Factory::create()

我真的不明白为什么它期望一个字符串列的数组。

4

1 回答 1

2

'name' => $this->faker->words将返回一个单词数组。

您可以调用底层方法并通过将 true 作为第二个参数传递来告诉它返回一个字符串:

$this->faker->words(3, true) // 3 is the number of words which is the default

或者你可以使用类似的东西sentence

$this->faker->sentence

words() 文档

于 2021-06-01T06:52:20.283 回答