传递给 Illuminate\Database\Grammar::parameterize() 的 Laravel 工厂参数 1 必须是数组类型,给定字符串

4 php laravel laravel-seeding laravel-factory laravel-8

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

\n

我的迁移有:

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

我的模型有:

\n
class Post extends Model\n{\n    use HasFactory, SoftDeletes;\n\n    public function user()\n    {\n        return $this->belongsTo(User::class);\n    }\n\n    public function setSlugAttribute($value)\n    {\n        $this->attributes['slug'] = Str::slug($this->name);\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我厂有:

\n
public function definition()\n{\n    return [\n        'name' => $this->faker->words,\n        'desc' => $this->faker->sentence,\n        'user_id' => rand(1,10)\n    ];\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我的帖子播种机有:

\n
public function run()\n{\n    Post::factory()->times(13)->create();\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我的主要 DatabaseSeeder 运行一个用户播种器,可播种 10 个用户。然后一个帖子播种者播种了 13 个帖子。

\n

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

\n
\n

类型错误

\n

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

\n

在供应商/laravel/framework/src/Illuminate/Database/Grammar.php:136\n132\xe2\x96\x95 *\n133\xe2\x96\x95 * @param array $values\n134\xe2\x96\x95 * @return string\n135\xe2\x96\x95 */ \xe2\x9e\x9c 136\xe2\x96\x95 公共函数parameterize(array $values)\n137\xe2\x96\x95 {\n138\xe2\x96\ x95 返回 implode(', ', array_map([$this, '参数'], $values));\n139\xe2\x96\x95 }\n140\xe2\x96\x95

\n
  +1 vendor frames    2   [internal]:0\n  Illuminate\\Database\\Query\\Grammars\\Grammar::Illuminate\\Database\\Query\\Grammars\\{closure}("Odio\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
  +13 vendor frames    16  database/seeders/PostsSeeder.php:17\n  Illuminate\\Database\\Eloquent\\Factories\\Factory::create()\n
Run Code Online (Sandbox Code Playgroud)\n
\n

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

\n

Rwd*_*Rwd 9

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

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

$this->faker->words(3, true) // 3 is the number of words which is the default
Run Code Online (Sandbox Code Playgroud)

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

$this->faker->sentence
Run Code Online (Sandbox Code Playgroud)

Words() 文档