函数 Database\Seeders\DatabaseSeeder::Database\Seeders\{closure}() 的参数太少

Too few arguments to function Database\Seeders\DatabaseSeeder::Database\Seeders\{closure}()

我想测试我的数据库,我已经创建了工厂,下面是我的种子文件中的代码

public function run()
{
    Category::factory()->count(10)->create();

    User::factory()
        ->has(Profile::factory()->state(function (array $attributes, User $user) {
            return ['user_id' => $user->id];
        }))
        ->has(Post::factory()->count(50)
            ->state(function (array $attributes, User $user, Category $category) {
            return ['user_id' => $user->id, 'category_id' => $category->id];
        })
        ->has(Comment::factory()->count(3))
            ->state(function (array $attributes, User $user, Post $post) {
            return ['user_id' => $user->id, 'category_id' => $post->id];
        }))
        ->create();


}

我想创建一些类别和 1 个或多个带有附加配置文件、帖子和评论的用户。有人可以检查我的代码是否正确,因为它给出了以下错误:

Too few arguments to function Database\Seeders\DatabaseSeeder::Database\Seeders{closure}(), 2 passed in D:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\Factory.php on line 422 and exactly 3 expected

at D:\xampp\htdocs\blog\database\seeders\DatabaseSeeder.php:28 24▕ ->has(Profile::factory()->state(function (array $attributes, User $user) { 25▕ return ['user_id' => $user->id]; 26▕ })) 27▕ ->has(Post::factory()->count(50) ➜ 28▕ ->state(function (array $attributes, User $user, Category $category) { 29▕ return ['user_id' => $user->id, 'category_id' => $category->id]; 30▕ }) 31▕ ->has(Comment::factory()->count(3)) 32▕ ->state(function (array $attributes, User $user, Post $post) {

1
D:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\Factory.php:422 Database\Seeders\DatabaseSeeder::Database\Seeders{closure}(Object(App\Models\User))

2
D:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Collections\Traits\EnumeratesValues.php:741 Illuminate\Database\Eloquent\Factories\Factory::Illuminate\Database\Eloquent\Factories{closure}(Object(Closure))

你的第二个和第三个闭包有问题:

->state(function (array $attributes, User $user, Category $category)

您不能期望超过 $attributes 和创建的父模型(在本例中为 $user)。这个$category参数导致问题,你需要在闭包外获取这个对象。