Laravel中如何通过传入变量$id查询MySQL表中对应seller_id的uniname数据
代码问题修正
你的代码存在两个核心问题:
where条件中用单引号包裹$id,PHP单引号不会解析内部变量,实际查询时匹配的是字符串$id而非传入的参数值- 仅调用了
where方法构造查询条件,没有执行查询获取结果集,此时传递到前端的是查询构造器对象而非数据
修正后的控制器代码
public function manage_seller_profile($id) { $divisions = Division::orderBy('id','asc')->get(); $districts = District::orderBy('id','asc')->get(); $seller_profile = Seller_info::find($id); // 去掉$id外层的单引号,末尾加get()执行查询获取所有匹配数据 $university = DB::table('universities')->where('seller_id', $id)->get(); return view('Backend.pages.seller.manage_seller_profile', compact('seller_profile', 'districts', 'divisions', 'university')); }
如果仅需要uniname字段,可以优化查询减少性能消耗:
$university = DB::table('universities')->where('seller_id', $id)->select('uniname')->get();
前端输出示例(Blade模板)
在manage_seller_profile.blade.php中可以直接遍历输出所有匹配的uniname:
{{-- 空数据判断 --}} @if($university->isEmpty()) <p>当前卖家暂无关联院校数据</p> @else @foreach($university as $item) <p>{{ $item->uniname }}</p> @endforeach @endif
内容的提问来源于stack exchange,提问作者Oni Sama
相关产品推荐
相关产品推荐

