Laravel v5.5执行php artisan migrate --seed报错及新增字段方法咨询
email_verified_at字段缺失错误 错误原因分析
你遇到的SQLSTATE[42S22]: Column not found错误,核心原因是你的users数据库表中不存在email_verified_at字段,但数据种子(Seeder)或模型的批量赋值逻辑里,尝试往这个字段插入数据了。
需要注意的是,email_verified_at是Laravel 5.7及以后版本才默认加入用户表的字段(用于邮箱验证功能),而你使用的Laravel 5.5,默认的users表迁移文件里并没有这个字段。
快速解决当前错误
按照以下步骤添加缺失的字段:
生成添加字段的迁移文件
在终端运行命令,创建一个针对users表的迁移:php artisan make:migration add_email_verified_at_to_users_table --table=users编辑迁移文件
打开生成的迁移文件(路径:database/migrations/[时间戳]_add_email_verified_at_to_users_table.php),修改up和down方法:public function up() { Schema::table('users', function (Blueprint $table) { // 添加可空的时间戳字段,匹配种子里的时间值或空值场景 $table->timestamp('email_verified_at')->nullable(); }); } public function down() { Schema::table('users', function (Blueprint $table) { // 回滚操作:删除该字段 $table->dropColumn('email_verified_at'); }); }执行迁移并重新运行种子
先执行迁移创建字段:php artisan migrate然后再运行种子命令:
php artisan db:seed
如果你还没有执行过初始的
users表迁移,可以直接修改原始的create_users_table迁移文件,添加email_verified_at字段,再执行php artisan migrate即可(无需单独创建新迁移)。
Laravel中为数据库表新增字段的通用方法
不管是添加email_verified_at还是其他字段,都可以遵循以下通用流程:
步骤1:创建迁移文件
使用make:migration命令,指定要修改的表名,命名格式建议为add_[字段名]_to_[表名]_table:php artisan make:migration add_[字段名]_to_[表名]_table --table=[表名]示例:给
posts表添加published_at字段php artisan make:migration add_published_at_to_posts_table --table=posts步骤2:定义字段与回滚逻辑
在迁移文件的up方法中定义要添加的字段(支持多种字段类型:字符串、整数、布尔值等),down方法定义回滚时的删除操作:public function up() { Schema::table('posts', function (Blueprint $table) { // 可空时间戳字段 $table->timestamp('published_at')->nullable(); // 唯一字符串字段 $table->string('slug')->unique(); // 默认值为0的整数字段 $table->integer('view_count')->default(0); // 默认值为false的布尔字段 $table->boolean('is_featured')->default(false); }); } public function down() { Schema::table('posts', function (Blueprint $table) { // 可一次性删除多个字段 $table->dropColumn(['published_at', 'slug', 'view_count', 'is_featured']); }); }步骤3:执行迁移
运行命令应用迁移,将字段添加到数据库表中:php artisan migrate步骤4:更新模型的批量赋值白名单
最后,别忘了在对应模型的$fillable数组中添加新增的字段,这样才能通过create()或update()等方法批量赋值:// 比如Post模型 protected $fillable = [ 'title', 'content', 'published_at', 'slug', 'view_count', 'is_featured' ];
内容的提问来源于stack exchange,提问作者tinoe m

