【问题标题】:Laravel 8 Error No Found : Class "Database\Factories\Backend\AdminFactory"未找到 Laravel 8 错误:类“Database\Factories\Backend\AdminFactory”
【发布时间】:2021-01-02 14:02:30
【问题描述】:

我在 database->factories 目录中有这个 AdminFactory.php 文件:

<?php

namespace Database\Factories;

use App\Models\Backend\Admin;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => 'Admin',
            'email' => 'admin@admin.com',
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
}

当我尝试运行此命令时: php artisan migrate --seed

它在终端中显示此错误消息:

【问题讨论】:

  • 你必须把工厂放在database\Factories\Backend 或者告诉模型在哪里找到你的工厂,因为它不能自动找到它,因为命名空间/命名
  • 我在 Factories 文件夹中没有任何名为 Backend 的文件夹
  • 将工厂放在那个目录中...然后创建目录,如果您移动它,您还必须更改该工厂声明的命名空间...或者如之前所述,您可以选择告诉模型返回一个特定的工厂,你选择做哪一个
  • 它只是自动连接需要特定的命名空间和类名,一旦你违背了这个约定,你就必须做出调整......祝你好运:)

标签: php laravel git command laravel-8


【解决方案1】:

尝试在包中使用工厂时遇到了这个问题。我通过覆盖HasFactory::newFactory() 方法解决了这个问题。

class LegacyCategory extends Model
{
    use HasFactory;

    ...    

    /**
     * Create a new factory instance for the model.
     *
     * @return \Illuminate\Database\Eloquent\Factories\Factory
     */
    protected static function newFactory()
    {
        return new LegacyCategoryFactory();
    }           
}

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2021-01-08
    • 2021-06-07
    • 2022-10-07
    • 2019-09-12
    • 1970-01-01
    相关资源
    最近更新 更多