Laravel执行migrate:refresh --seed报错:firstname字段无默认值
问题描述
执行php artisan migrate:refresh --seed时触发数据库错误:
SQLSTATE[HY000]: General error: 1364 Field 'firstname' doesn't have a default value (Connection: mysql, SQL: insert into
users(updated_at,created_at) values (2023-07-06 14:12:05, 2023-07-06 14:12:05))
相关代码如下:
User模型的$fillable属性
protected $fillable = [ 'first name', 'last name', 'phoneNumber', 'email', 'password', 'image', 'reg_token' ];
迁移文件
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('firstname'); $table->string('lastname'); $table->string('email')->unique(); $table->string('profile_picture'); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->timestamps(); $table->string('phoneNumber'); $table->string('reg_token'); $table->string('person_type')->nullable(); $table->unsignedBigInteger('person_id')->nullable(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('users'); } };
UserFactory
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User> */ class UserFactory extends Factory { /** * Define the model's default state. * * @return array<string, mixed> */ public function definition(): array { return [ 'firstname' => fake()->name(), 'lastname' => fake()->name(), 'email' => fake()->unique()->safeEmail(), 'profile_picture' => fake()->imageUrl(), 'email_verified_at' => now(), 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'phoneNumber' => "0123456789", 'reg_token' => Str::random(10), ]; } /** * Indicate that the model's email address should be unverified. */ public function unverified(): static { return $this->state(fn(array $attributes) => [ 'email_verified_at' => null, ]); } }
解决方案
问题核心是模型$fillable字段与数据库、工厂的字段完全不匹配,Laravel的批量赋值机制会阻止未在$fillable中声明的字段写入数据库,导致工厂生成的字段值无法插入,最终触发MySQL非空字段无默认值的错误。需按以下步骤修正:
统一字段命名与对应关系
数据库和工厂使用的是firstname、lastname、profile_picture,但模型$fillable里写的是first name、last name(带空格)、image,完全不匹配,需修改模型的$fillable为:protected $fillable = [ 'firstname', 'lastname', 'phoneNumber', 'email', 'password', 'profile_picture', 'reg_token', 'email_verified_at' ];验证字段一致性
确保$fillable中包含所有需要通过批量赋值写入的字段(比如工厂里用到的email_verified_at),且字段名与数据库完全一致。
完成以上修改后,重新执行php artisan migrate:refresh --seed即可解决问题。
内容的提问来源于stack exchange,提问作者Djebarra Rabah Abderrazak
相关产品推荐
相关产品推荐

