Laravel 工厂播种问题

Problem with Laravel Seeding with Factories

我对 Laravel 工厂播种有疑问:

我有三个 table usersproductsproducts_categories。我有一个在 ProductSeeder 中调用的 ProductFactory class。最后,我有我的 DatabaseSeeder 执行所有播种者。

当我 运行 php artisan db:seed 时,出现 table 名称错误。当我的 table 名字是 products_categories 时,播种机尝试将值插入 product_categories。我不知道如何解决这个错误。

Seeding: ProductSeeder

   Illuminate\Database\QueryException  : SQLSTATE[42S02]: Base table or view not found: 1146 Table 'b2-laravel-uf.product_categories' doesn't exist (SQL: insert into `product_categories` (`name`, `updated_at`, `created_at`) values (Mathématiques, 2019-11-22 13:32:52, 2019-11-22 13:32:52))

ProductFactory.php

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Product;
use Faker\Generator as Faker;

$factory->define(Product::class, function (Faker $faker) {
    return [
        'reference' => $faker->randomNumber(6),
        'name' => $faker->sentence(5),
        'description' => $faker->text(200),
        'price_ht' => 9.99,
        'category_id' => factory(App\ProductCategory::class),
        'owner_id' => factory(App\User::class)
    ];
});

ProductSeeder.php

<?php

use Illuminate\Database\Seeder;

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

DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

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

产品类别迁移table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products_categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

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

提前谢谢你。

可能是由于 Laravel 以及它如何 'generate' 如果未明确声明 table 名称,所以只需在 ProductCategory 中声明 table 名称即可型号:

protected $table = 'product_categories'

您需要将 generated table 名称更改为 products_categories,

在您的 ProductCategory 模型中,

protected $table = 'product_categories';