Laravel 8 BadMethodCallException

Laravel 8 BadMethodCallException

我正在学习 laravel 8,但我一直收到此错误

   BadMethodCallException 

  Call to undefined method App\Models\Question::factory()

  at C:\Users\USER\Desktop\laravels\qna\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:50
     46▕      * @throws \BadMethodCallException
     47▕      */
     48▕     protected static function throwBadMethodCallException($method)
     49▕     {
  ➜  50▕         throw new BadMethodCallException(sprintf(
     51▕             'Call to undefined method %s::%s()', static::class, $method
     52▕         ));
     53▕     }
     54▕ }

  • Bad Method Call: Did you mean App\Models\Question::toArray() ?

  1   C:\Users\USER\Desktop\laravels\qna\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:36
      Illuminate\Database\Eloquent\Model::throwBadMethodCallException("factory")

  2   C:\Users\USER\Desktop\laravels\qna\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1993
      Illuminate\Database\Eloquent\Model::forwardCallTo(Object(Illuminate\Database\Eloquent\Builder), "factory")

我在 DatabaseSeeder.php 文件中,我认为问题出在这段代码中:

public function run()
{
    \App\Models\User::factory(3)->create()->each(function($u) {
        $u->questions()
          ->saveMany(
            //   factory(App\Question::class, rand(1,5))->make()
            \App\Models\Question::factory(rand(1,5))->make()
          );
    });
}

我在 tinker 中 运行 这个命令后得到了类似的东西:

>>> \App\Models\Question::factory(3)->make();

Link 回购是 here 任何指针将不胜感激!

因此,在您的模型中,您需要特征 'HasFactory' 才能使用它