【问题标题】:Laravel 8 - Model factory class not found when creating a dummy dataLaravel 8 - 创建虚拟数据时找不到模型工厂类
【发布时间】:2021-02-02 09:31:51
【问题描述】:

我目前正在关注 laracasts 从头开始​​的 laravel 系列,但由于该系列的 laravel 版本是 laravel 6,因此我陷入了这个问题。我已经在这里搜索了答案并找到了类似的线程,但我的情况不同,因为我安装了新的 laravel 8 版本。

我正在使用 tinker 上的这个命令使用工厂模型类创建一个虚拟数据:

Article::factory()->count(1)->make();

这是我得到的错误:

PHP Fatal error:  Class 'Article' not found in Psy Shell code on line 1

这是我的模型 Article.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasFactory;
    protected $guarded = [];
}

这是我的工厂 ArticleFactory.php

<?php

namespace Database\Factories;

use App\Models\Article;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class ArticleFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Article::class;

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

我尝试使用用户的默认模型和工厂创建一个虚拟数据,它工作得很好。我在 tinker 上使用了相同的代码:

>>> User::factory()->count(1)->make();
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.
=> Illuminate\Database\Eloquent\Collection {#3289
     all: [
       App\Models\User {#3294
         name: "Lane Maggio I",
         email: "tromp.deion@example.com",
         email_verified_at: "2020-10-19 15:08:24",
       },
     ],
   }

【问题讨论】:

  • 你在创建模型/工厂后是否运行composer dump-autoload?有时,tinker(和其他控制台命令)中缺少类定义,直到该命令运行为止。
  • 是的,我将 make() 更改为 create() 以便将其保存在数据库中。

标签: php laravel


【解决方案1】:

在文件顶部添加以下sn-p;

use App\Models\Article;

【讨论】:

  • 哇,非常感谢,我将它添加到了 Article.php 本身。
猜你喜欢
  • 2021-01-04
  • 2021-01-26
  • 2023-03-03
  • 2023-02-04
  • 2021-03-05
  • 2020-12-28
  • 2017-04-11
  • 2021-11-06
  • 2021-04-11
相关资源
最近更新 更多