4 php laravel laravel-seeding laravel-factory laravel-8
当尝试在 laravel 8 中运行工厂时,我收到此错误。我已经查看了几篇有关此错误的帖子,但它们似乎都来自直接错误地保存/创建。不使用工厂。所以我不确定为什么工厂没有正确保存它。
\n我的迁移有:
\npublic 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}\nRun Code Online (Sandbox Code Playgroud)\n我的模型有:
\nclass 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}\nRun Code Online (Sandbox Code Playgroud)\n我厂有:
\npublic function definition()\n{\n return [\n 'name' => $this->faker->words,\n 'desc' => $this->faker->sentence,\n 'user_id' => rand(1,10)\n ];\n}\nRun Code Online (Sandbox Code Playgroud)\n我的帖子播种机有:
\npublic function run()\n{\n Post::factory()->times(13)->create();\n}\nRun 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
\nRun Code Online (Sandbox Code Playgroud)\n+1 vendor frames 2 [internal]:0\n Illuminate\\Database\\Query\\Grammars\\Grammar::Illuminate\\Database\\Query\\Grammars\\{closure}("Odio\nvoluptatem quis Facere possimus ut.", "desc")
\nRun Code Online (Sandbox Code Playgroud)\n+13 vendor frames 16 database/seeders/PostsSeeder.php:17\n Illuminate\\Database\\Eloquent\\Factories\\Factory::create()\n
我真的不明白为什么它需要一个字符串列的数组。
\n'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)
| 归档时间: |
|
| 查看次数: |
5486 次 |
| 最近记录: |