Laravel8一对多关联同时保存方法及Carbon日期格式化报错解决
问题解决步骤
1. 修复Carbon日期解析错误
你报错的直接原因是Carbon::createFromFormat的格式参数写错了:
- PHP日期格式规则里没有
dd/mm/YYYY这种写法,正确的日/月/四位年格式是d/m/Y - 直接用年份相减计算年龄的方式不准确,未考虑当前日期是否已经过了当年生日,建议直接用Carbon自带的
age属性计算实际年龄
修改后的年龄计算代码:
// 适配24/8/1995这类格式解析日期 $birthDate = Carbon::createFromFormat('d/m/Y', trim($request->date_naissance)); $age = $birthDate->age;
2. 修复前端表单冲突问题
- 表单中存在两个
name="cine"的字段(casting的CIN和监护人的CIN),提交时后一个会覆盖前一个的值,需要修改监护人的字段名避免冲突,比如改成name="representant_cine" - 出生地输入框的
name属性写错了:当前是name="lien_naissance",需要改成name="lieu_naissance"才能和后端接收字段对应。
3. 修复模型与关联字段错误
3.1 修改Casting模型
- 把关联字段
id_representant加到$fillable属性里,否则无法写入数据库 - 关联方法调整为正确的外键配置:
class Casting extends Model { use HasFactory; protected $fillable = [ "id_casting", "nom", "prenom", "cine", "date_naissance", "lieu_naissance", "mineur", "id_representant" ]; public function representant() { return $this->belongsTo(Representant::class, 'id_representant', 'id_representant'); } }
3.2 补充缺失字段的赋值规则
representants表的actif字段没有默认值,存入时需要手动赋值,比如默认设为1表示启用castings表的mineur字段没有默认值,需要根据年龄赋值,小于18可存'1',否则存'0'。
4. 修复控制器存储逻辑
- 新增数据库事务,保证两张表数据一致性,避免出现监护人存成功但casting存失败的脏数据
- 修复关联字段赋值错误:你之前写的
$castings->representant_id和表中的id_representant字段名不一致 - 补充else分支的Casting保存逻辑
修改后的控制器代码:
use Illuminate\Support\Facades\DB; public function store(Request $request) { return DB::transaction(function () use ($request) { // 计算真实年龄 $birthDate = Carbon::createFromFormat('d/m/Y', trim($request->date_naissance)); $age = $birthDate->age; $castingData = $request->only(['nom', 'prenom', 'cine', 'date_naissance', 'lieu_naissance']); $castingData['mineur'] = $age < 18 ? '1' : '0'; if ($age < 18) { // 先存监护人信息 $representant = Representant::create([ 'nom_prenom' => $request->nom_prenom, 'cine' => $request->representant_cine, // 和修改后的表单字段名对应 'lien_casting' => $request->lien_casting, 'actif' => 1 ]); // 关联监护人ID到casting表 $castingData['id_representant'] = $representant->id_representant; } // 保存casting数据 Casting::create($castingData); return response()->json(['status' => 'success']); }); }
内容的提问来源于stack exchange,提问作者melissa maya
相关产品推荐
相关产品推荐

