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
相关产品推荐
相关产品推荐

