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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:36:05