是什么导致此 Laravel 8 应用程序出现 'Unknown format "factory"' 错误?

What causes the 'Unknown format "factory"' error in this Laravel 8 app?

我正在开发一个包含用户和帖子的 Laravel 8 应用程序。

objective是为了创建一堆帖子(我已经有用户了)。

namespace Database\Factories;
// import Post model
use App\Models\Post;
// import User model
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory {
  /**
   * The name of the factory's corresponding model.
   *
   * @var string
   */
   protected $model = Post::class;
 
  /**
   * Define the model's default state.
   *
   * @return array
   */
   public function definition() {
    return [
            'title' => $this->faker->sentence(3),
            'description' => $this->faker->text,
            'content' => $this->faker->paragraph,
            'user_id' => $this->faker->factory(App\Models\User::class),
        ];
    }
}

问题

I 运行 php artisan tinker 然后 Post::factory()->count(100)->create() 在终端中,我得到:

InvalidArgumentException with message 'Unknown format "factory"'

更新

我将我的 return 语句替换为:

 return [
    'title' => $this->faker->sentence(3),
    'description' => $this->faker->text,
    'content' => $this->faker->paragraph,
    'user_id' => User::factory(),
];

我在终端中得到这个:

Class 'Database\Factories\UserFactory' not found

问题:

  1. 我的错误在哪里?
  2. 我收到错误 Class 'Database\Factories\UserFactory' not found 是否意味着我需要 创建一个 UserFactory 工厂?因为没有一个。 (我想了 创建帖子,而不是用户)。

我想没有 $this->faker->factory(..)

你可以做到

'user_id' => App\Models\User::factory()->create()->id,

编辑: 'user_id' => App\Models\User::factory(),

创建一个 UserFactory 工厂并使用下面的 return 语句成功了:

return [
    'title' => $this->faker->sentence(3),
    'description' => $this->faker->text,
    'content' => $this->faker->paragraph,
    'user_id' => User::factory(),
];

因此,PostFactory class 看起来像这样:

class PostFactory extends Factory {
  /**
   * The name of the factory's corresponding model.
   *
   * @var string
   */
   protected $model = Post::class;
 
  /**
   * Define the model's default state.
   *
   * @return array
   */
   public function definition() {
        return [
                'title' => $this->faker->sentence(3),
                'description' => $this->faker->text,
                'content' => $this->faker->paragraph,
                'user_id' => User::factory(),
        ];
    }
}