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

如何在Laravel控制器中从双表取数据并将$countries加入State查询串?

Laravel多表数据获取与变量传递解决方案

步骤说明:

  • 取消注释获取国家数据的代码,若需性能优化可指定返回字段
  • 将$countries直接添加到Inertia渲染的参数数组中,与states、filters同级即可,无需修改原有State查询的withQueryString()逻辑(该方法仅对分页的states数据生效,不影响其他变量传递)

修改后的完整代码:

public function index(){
    $countries = Country::all();
    // 性能优化可选:只返回需要的字段,比如id和name
    // $countries = Country::select('id', 'name')->get();
    
    $perPage = request('perPage') ?: 5;
    return Inertia::render('State/Index',[
        'states' => State::query()
            ->when(request('search'), function($query, $search){
                $query->where('name', 'like', "%{$search}%");
            })
            ->paginate($perPage)
            ->withQueryString(),
        'countries' => $countries, // 新增传递countries变量
        'filters' => request()->only(['search', 'perPage']),
    ]);
}

补充说明:

  • 代码中把Requests替换成了Laravel更常用的辅助函数request(),两者功能一致,但写法更简洁
  • 前端组件中可以直接通过props.countries访问国家列表数据,不影响原有states分页和筛选逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:50:39