gpt4 book ai didi

php - Laravel 工厂播种问题

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:55 25 4
gpt4 key购买 nike

我在使用 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))

产品工厂.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();
}
}

数据库播种器.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');
}
}

提前谢谢你。

最佳答案

可能是由于 Laravel 以及它如何在未显式声明的情况下“生成”表名,因此只需在 ProductCategory 模型中声明表名如下:

protected $table = 'product_categories'

关于php - Laravel 工厂播种问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58995655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com