使用 tinker 生成用户和帖子时出错 (Laravel)

Error when using tinker to generate Users and Posts (Laravel)

我有以下 BlogPostFactory

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;


class BlogPostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->sentence,
            'body' => $this->faker->paragraph(30),
            'user_id' => User::factory(),
        ];
    }
}

我一直在尝试使用 tinker 生成帖子和用户,

 \App\Models\BlogPost::factory()->count(10)->create();

但我收到以下错误:

PHP Error:  Class "Database\Factories\User" not found in C:\Program Files\Ampps\www\example\database\factories\BlogPostFactory.php on line 19

有谁知道如何解决这个问题?感谢您的帮助!

您缺少 User class 上的命名空间。
默认情况下 PHP 采用当前命名空间 namespace Database\Factories;,因此出现错误。

Name resolution rules

  1. For unqualified names, if no import rule applies and the name refers to a class-like symbol, the current namespace is prepended. For example, new C() inside namespace A\B resolves to name A\B\C.

而不是:(不合格的名称)

// ...
'user_id' => User::factory(),
// ....

使用这个:(完全限定名称

// ...
'user_id' => \App\Models\User::factory(),
// ...

附录

不要忘记重新启动当前的修补程序会话。 (关闭当前的(exit;)并打开一个新的修补程序会话(php artisan tinker)。