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

Laravel中三表关联查询匹配RequestID的指定字段问题求助

原有代码错误点

  • 关联顺序错误:未关联test_bookings表时就提前关联nurses表,查询上下文不存在test_bookings.nurse_id字段,会触发字段不存在错误
  • 字段未指定所属表:RequestID同时存在于tests和test_bookings表中,不指定表前缀会触发字段歧义错误
  • 关联条件语法错误:tests.RequestID未包裹为字符串,查询构造器无法正常识别

正确实现代码

使用inner join的特性即可天然过滤test_bookings中RequestID不存在于tests表的记录,完全匹配你的需求:

$tests = DB::table('test_bookings')
    ->select(
        'test_bookings.RequestID',
        'test_bookings.bookingDate',
        'test_bookings.timeSlot',
        'nurses.name',
        'nurses.surname'
    )
    ->join('tests', 'test_bookings.RequestID', '=', 'tests.RequestID')
    ->join('nurses', 'test_bookings.nurse_id', '=', 'nurses.nurseID')
    ->get();

内容的提问来源于stack exchange,提问作者Convert.ToInt32

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:54:03