调用未定义的方法App\Models\Category::factory(),laravel相关。

20

我遇到了上述错误,并且这是复制日志


php artisan db:seed

   BadMethodCallException

  Call to undefined method App\Models\Category::factory()

  at vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
     46▕      * @throws \BadMethodCallException
     47▕      */
     48protected static function throwBadMethodCallException($method)
     49▕     {
  ➜  50throw new BadMethodCallException(sprintf(
     51'Call to undefined method %s::%s()', static::class, $method
     52▕         ));
     53▕     }
     54▕ }

  • Bad Method Call: Did you mean App\Models\Category::toArray() ?

      +3 vendor frames
  4   database/seeders/DatabaseSeeder.php:38
      Illuminate\Database\Eloquent\Model::__callStatic()

      +22 vendor frames
  27  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

由于错误发生在此处,因此以下是databaseseeder.php类:

<?php

namespace Database\Seeders;

use App\Models\Category;
use App\Models\Product;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Database\Seeder;

use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // \App\Models\User::factory(10)->create();

        DB::statement('SET FOREIGN_KEY_CHECKS=0');

        User::truncate();
        Category::truncate();
        Product::truncate();
        Transaction::truncate();
        DB::table('category_product')->truncate();

        $cantidadUsuarios = 200;
        $cantidadCategories = 30;
        $cantidadProductos = 1000;
        $cantidadTransacciones = 1000;

        \App\Models\User::factory()->count($cantidadUsuarios)->create();
        \App\Models\Category::factory()->count($cantidadUsuarios)->create();

        \App\Models\Product::factory()->count($cantidadTransacciones)->create()->each                                                                                           (
            function ($producto) {
                $categorias = Category::all()->random(mt_rand(1, 5))->pluck('id');
                $producto->categories()->attach($categorias);
            }
        );

        \App\Models\Transaction::factory()->count($cantidadTransacciones)->create();
    }
}

这是错误所在的代码行:

\App\Models\Category::factory()->count($cantidadUsuarios)->create();

这里我们有一个类别分类:

<?php

namespace App\Models;

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

class Category extends Model
{
    public $table = "categories";

    protected $fillable = [
        'name',
        'description',
    ];
}

这里是分类工厂:

<?php

namespace Database\Factories;

use App\Models\Category;
use Illuminate\Database\Eloquent\Factories\Factory;

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            //
             'name' => $this->faker->word,
            'description' => $this->faker->paragraph(1),
        ];
    }
}

这里是类别迁移:

<?php

use App\Models\Product;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description', 1000);
            $table->integer('quantity')->unsigned();
            $table->string('status')->default(Product::PRODUCTO_NO_DISPONIBLE);
            $table->string('image');
            $table->integer('seller_id')->unsigned();
            $table->timestamps();

            $table->foreign('seller_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

因为我是新手,找不到问题所在,所以我会发布所有你需要的内容。

5个回答

45
从Laravel 8开始,你需要在模型中使用工厂特性才能使用factory()方法。
class Category extends Model
{
   use HasFactory;

   ...
}

1
我在 Laravel 7.x 中遇到了“Fatal Error: Trait 'Illuminate\Database\Eloquent\Factories\HasFactory' not found”的错误。 - nice_dev
我认为更好的方法是在database/factories文件夹中为特定模型定义后,使用factory()方法运行种子。https://laravel.com/docs/7.x/seeding#running-seeders - nice_dev
2
@nice_dev 在 Laravel 7 中并不存在这个特性。事实上,在 Laravel 8 中重新设计了定义工厂的方式。在 Laravel 7 中,你需要使用 factory() 辅助函数来创建工厂,而不是像这样使用 Category::factory()->create();。我建议你升级到最新版本。拖延升级只会让问题变得更加困难。 - IGP
好的,我会升级。我假设这值得在你的答案中添加一条注释,即适用于Laravel 8及以上版本。 - nice_dev

12

按照以下代码:

<?php

namespace App\Models;

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

class Category extends Model
{
    use HasFactory;
}

4

将Trait添加到模型中 => 使用HasFactory

use Illuminate\Database\Eloquent\Factories\HasFactory;

class Model extends Model
{
    use HasFactory;
}

2
如果您使用的是 Laravel 8,那么 Illuminate\Database\Eloquent\Factories\HasFactory 已不再存在,所以只需将您的模型类包装在 factory() 方法中即可。
factory(App\Models\Category::class)->count($cantidadUsuarios)->create();

或者

factory(App\Category::class)->count($cantidadUsuarios)->create();

0

如果你正在使用 Tinker,添加 HasFactory 类后,只需结束当前会话并启动另一个会话即可。

- Ctr+c
- Php artisan tinker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接