You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中关联3张表并实现登录用户的验证数据更新

修改当前登录用户的Laravel验证记录指南

嘿,作为Laravel新手,你这个需求很典型,但你的现有代码还没关联到当前用户的专属记录哦——直接跑你写的代码会把所有用户里符合条件的验证记录都改掉,这可不是你想要的结果!

下面我给你两种靠谱的实现方式,推荐用第一种(Eloquent关联),更符合Laravel的优雅风格:

方式1:用Eloquent模型关联(推荐)

首先你得确保你的模型已经定义了正确的关联关系:

  • 在User模型里添加和Exam的关联:
public function exams()
{
    return $this->hasMany(Exam::class);
}
  • 在Exam模型里添加和Verification的关联:
public function verifications()
{
    return $this->hasMany(Verification::class);
}

有了关联之后,就能直接通过当前用户链式调用修改他的验证记录了:

// 仅修改当前登录用户的、符合条件的验证记录
Auth::user()->exams()->verifications()
    ->where('confirmation', 'non')
    ->where('modifier', 'oui')
    ->update(['confirmation' => 'oui']);

方式2:用查询构造器(原生SQL风格)

如果你不想用模型关联,也可以直接通过表关联来限定当前用户:

DB::table('verifications')
    // 关联Exams表,找到属于当前用户的考试
    ->join('exams', 'verifications.exam_id', '=', 'exams.id')
    // 限定只改当前登录用户的记录
    ->where('exams.user_id', Auth::id())
    // 你的原有条件
    ->where('verifications.confirmation', 'non')
    ->where('verifications.modifier', 'oui')
    // 更新字段
    ->update(['verifications.confirmation' => 'oui']);

重要注意事项

  • 一定要确保用户已经登录!可以加个判断避免未登录时报错:
if (Auth::check()) {
    // 执行上面的修改逻辑
}
  • 永远不要跳过「关联当前用户」的条件,不然会误改其他用户的数据,这在生产环境里是大问题!

内容的提问来源于stack exchange,提问作者Mehdi El Aissi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:47:33