Laravel, 调用未定义的函数 Database\Seeders\factory()

2022-08-30 14:05:33

我运行命令时收到标题错误:

php artisan db:seed

我的截图:enter image description here

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

ArticlesTableSeeder.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);
    }
}

提前感谢您的帮助!


答案 1

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

尝试更改:

ArticlesTableSeeder.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)

答案 2

这里提到的所有建议都是正确的。有时,如果您使用的是Laravel 8,则运行可能会解决您的问题。另外,如果你得到一个错误,然后确保你有而不是ModalFactory。并确保你在文章模型中使用HasFactory,就像这里一样。composer require laravel/legacy-factoriesClass 'Database\Factories\ArticleFactory' not foundclass ArticleFactory extends Factory

<?php

namespace App\Models;

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

class Article extends Model
{
    use HasFactory;
}

欲了解更多信息:Laravel 8 Modal Factory。


推荐