【问题标题】:Problem with Laravel Seeding with FactoriesLaravel 与工厂播种的问题
【发布时间】:2020-03-18 14:37:28
【问题描述】:

我对使用工厂的 Laravel 播种有疑问:

我有三个表usersproductsproducts_categories。我有一个在ProductSeeder 中调用的ProductFactory 类。最后,我的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');
    }
}

提前谢谢你。

【问题讨论】:

  • 请同时发布模型

标签: php mysql laravel laravel-seeding


【解决方案1】:

可能是由 Laravel 引起的,如果没有明确声明它是如何“生成”表名的,所以只需在 ProductCategory 模型中声明表名如下:

protected $table = 'product_categories'

【讨论】:

    【解决方案2】:

    需要将generated表名改为products_categories

    在您的ProductCategory 模型中,

    protected $table = 'product_categories';
    

    【讨论】:

      猜你喜欢
      • 2017-08-02
      • 2015-09-16
      • 1970-01-01
      • 2017-04-07
      • 2015-08-26
      • 1970-01-01
      • 2019-09-29
      • 2018-08-28
      • 2019-09-21
      相关资源
      最近更新 更多