【问题标题】:Target class [Database\Seeders\MockNotification] does not exist in LaravelLaravel 中不存在目标类 [D​​atabase\Seeders\MockNotification]
【发布时间】:2021-08-30 19:31:21
【问题描述】:

我正在使用播种器类来播种数据库中的表

<?php
namespace Database\Seeders;
class MockNotification extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
        Notification::factory()->times(2)->create();
    }
}

我在 DatabaseSeeder 中调用这个类


<?php
namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Database\Seeders\NotificationTypeSeeder;
use Database\Seeders\MockNotification;
class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UserSeeder::class);
        $this->call([NotificationTypeSeeder::class]);
        $this->call([MockNotification::class]);
    }
}

我收到了这个错误

目标类 [D​​atabase\Seeders\MockNotification] 不存在。

虽然我已经在 DatabaseSeeder 文件中导入了 MockNotification 类

【问题讨论】:

    标签: php laravel laravel-seeding


    【解决方案1】:

    你的问题真的很容易解决,你必须在LARAVEL_ROOT_FOLDER/database/seeders 中有你的MockNotification 类,然后将它添加到你的类的顶部namespace Database\Seeders;

    你的DatabaseSeeder 类也应该有namespace Database\Seeders;composer 需要它来执行 PSR-4 自动加载。

    你的播种机应该是这样的:

    namespace Database\Seeders;
    
    use Illuminate\Database\Seeder;
    
    class MockNotification extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run()
        {
            Notification::factory()->times(2)->create(); // Add this use on top
        }
    }
    

    【讨论】:

    • 您能否在答案中添加一些代码
    • @needgfasap 我更新了我的答案,记得检查文件在哪里,请分享路径
    【解决方案2】:

    在种子文件的开头添加以下行

    namespace Database\Seeders;
    

    然后在终端执行以下操作

    composer dumpautoload
    

    【讨论】:

      【解决方案3】:

      添加

      namespace Database\Seeders;
      

      到这两个文件。

      这是标准 PSR-4。

      【讨论】:

      • 我刚刚添加了命名空间 Database\Seeders;这两个文件是我在为数据库播种时得到的原因:目标类 [D​​atabase\Seeders\MockNotificationSeeder] 不存在。
      • 将 MockNotification 文件重命名为 MockNotificationSeeder。在文档laravel.com/docs/8.x/seeding 中使用此协议。
      • 已经在两个文件中添加了命名空间 Database/Seeders,但仍然出现同样的错误!
      猜你喜欢
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2021-04-02
      • 2021-11-23
      • 1970-01-01
      • 2021-01-25
      • 2021-04-09
      相关资源
      最近更新 更多