Laravel 工厂正在创建名称为 Id 而不是给定名称的 PK 列

Laravel factory is creating PK column with the name Id instead of the given one

我有以下工厂:

$factory->define(App\Product::class, function (Faker $faker) {
    return [
        'product_name' => $faker->sentence($nbWords = 4, $variableNbWords = true),
        'product_description' => $faker->paragraph($nbSentences = 6, $variableNbSentences = true),
        'product_price' => $faker->numberBetween($min=500, $max=2000),
    ];
});

以及以下迁移:

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('product_id');
            $table->string('product_name', 356)->nullable(false);
            $table->longText('product_description')->nullable();
            $table->integer('product_price')->nullable(false);
            $table->timestamps();
        });
    }

在运行工厂打印出一个新创建的产品后,它说PK是'id'而不是'product_id'。当尝试访问 $product->product_id 时返回 null,因为根据工厂显然不存在。

在检查数据库时 table 我可以确认列名为 product_id 而不是 'id'.

我已经运行:

composer dump-autoload

然后 运行 再次迁移,但仍然返回错误数据。

谢谢

您可以更改为:

$table->integer('product_id')->primary();

根据文档,您应该通过在模型中进行设置来覆盖默认值。

protected $primaryKey = 'product_id';

不要忘记对您的 table 关系进行必要的更改(hasManys、belongTos 等...)