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

Laravel控制器中Join结合Where条件使用及报错排查

解决Call to undefined method stdClass::get()报错问题

错误原因

你的show方法中,->where('id', $id)->first()已经返回了单个stdClass对象(对应匹配id的单条数据),但你紧接着调用了->get()。get()是Laravel查询构建器专属方法,stdClass对象并不具备这个方法,因此触发报错。

修正后的代码

移除多余的->get(),同时建议给where条件的id指定表名(避免多表查询时字段歧义),优化变量名和重复的查询字段:

public function show($id)
{
    $complaint = DB::table('complaint')
        ->select([
            'complaint.id',
            'complaint.createdDate',
            'complaint.user_id',
            'complaint.complaint_title',
            'tbl_users.phone',
            'tbl_users.email'
        ])
        ->join('tbl_users', 'complaint.user_id', '=', 'tbl_users.id')
        ->where('complaint.id', $id)
        ->first();

    return $complaint;
    // 若需返回视图,可改为:return view('admin.complaint-detail', compact('complaint'));
}

额外优化说明

  • 变量名从$complaints改为$complaint,符合单条数据的语义
  • 移除了select中重复的complaint.createdDate字段,精简查询语句

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:39:35