使用Laravel如何将带yes/no单选框的调查表单数据存入MySQL
问题修复方案
首先你现有迁移文件存在两个需要先修正的前置问题:
- 表名不统一:up方法中创建的是
posts表,但down方法删除的是survey_posts表,和迁移类名CreateSurveyPostsTable对应的Laravel约定表名不符,需要统一为survey_posts。 - 字段名使用了横杠
-:SQL中横杠默认是减号运算符,直接使用带横杠的字段名会触发语法错误,建议替换为下划线_,比如sq_symptoms、sq_travel、sq_contact。
yes/no单选字段的类型选择
有两种常用的最优方案,可根据你的需求选择:
方案1:boolean类型(推荐)
使用Laravel提供的boolean字段方法:
$table->boolean('sq_symptoms')->comment('是否有症状:1=是/yes,0=否/no');
对应MySQL底层是TINYINT(1)类型,仅占1字节空间,存储和查询效率最高。前端提交的yes/no值只需在控制器中做简单转换即可:$validated['sq_symptoms'] = $request->input('sq_symptoms') === 'yes' ? 1 : 0;。
方案2:enum枚举类型
如果需要直接在数据库存储yes/no字符串,不需要额外做值转换,可以使用枚举类型:
$table->enum('sq_symptoms', ['yes', 'no'])->comment('是否有症状:yes=是,no=否');
好处是前端提交的选项值可以直接入库,缺点是后续如果要新增选项(比如增加"未填写"选项)需要修改表结构。
修正后的完整迁移代码
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSurveyPostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('survey_posts', function (Blueprint $table) { $table->id(); $table->string('fname')->comment('名'); $table->string('lname')->comment('姓'); $table->string('id_number')->comment('身份证号'); $table->string('mobile')->comment('手机号'); // 使用boolean方案保留以下三行,用enum方案则注释替换 $table->boolean('sq_symptoms')->comment('是否有相关症状:1=是/yes,0=否/no'); $table->boolean('sq_travel')->comment('是否有风险地区旅居史:1=是/yes,0=否/no'); $table->boolean('sq_contact')->comment('是否有密接史:1=是/yes,0=否/no'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('survey_posts'); } }
提示:如果之前已经执行过该迁移,需要先运行
php artisan migrate:rollback回滚,或者直接删除数据库里的survey_posts表和migrations表中对应的迁移记录,再重新执行php artisan migrate即可生效。
内容的提问来源于stack exchange,提问作者Terence - AI FX
相关产品推荐
相关产品推荐

