Laravel带工厂播种的问题

时间:2019-11-22 13:50:22

标签: php mysql laravel laravel-seeding

我在工厂Laravel播种方面遇到问题:

我有三个表usersproductsproducts_categories。我有一个ProductFactory叫的ProductSeeder类。最后,我有DatabaseSeeder处决所有播种机。

运行php artisan db:seed时,表名称出现错误。我的表名称为product_categories时,播种器尝试将值插入products_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);
    }
}

“产品类别迁移”表

<?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');
    }
}

谢谢。

2 个答案:

答案 0 :(得分:2)

可能是由于Laravel以及如果未显式声明它如何“生成”表名引起的,因此只需按照ProductCategory模型中的说明声明表名即可:

protected $table = 'product_categories'

答案 1 :(得分:1)

您需要将generated表名更改为products_categories

在您的ProductCategory模型中,

protected $table = 'product_categories';