首页 > 解决方案 > Laravel,调用未定义函数 Database\Seeders\factory()

问题描述

运行命令时出现标题错误:

php artisan db:seed

我的截图: 在此处输入图像描述

我不知道这个问题来自哪里。我正在寻找代码示例和解决方案,但我没有找到任何东西:(

文章TableSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
// use Laracasts\TestDummy\Factory as TestDummy;

class ArticlesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Models\Article::class, 30)->create();
    }
}

文章工厂.php

<?php

namespace Database\Factories;

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

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $faker->text(50),
            'body' => $faker->text(200)
        ];
    }
}

DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(ArticlesTableSeeder::class);
    }
}

预先感谢您的帮助!

标签: phplaravellaravel-8

解决方案


在 laravel 8 中,删除了默认路由命名空间。

尝试改变:

文章TableSeeder.php:

 factory(App\Models\Article::class, 30)->create();

至:

\App\Models\Article::factory()->count(30)->create(); 

文章工厂.php:

protected $model = App\Models\Article::class;

至:

protected $model = \App\Models\Article::class;

你可能不得不改变:

 'title' => $faker->text(50),
            'body' => $faker->text(200)

至:

 'title' => $this->faker->text(50),
        'body' => $this->faker->text(200)

推荐阅读