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

Laravel如何根据请求查询参数返回对应货币汇率集合?

问题根源

你的代码存在3个核心问题:

  • 取请求参数错误:$request->all()会获取所有请求参数,而非仅获取currency数组
  • 数据库查询逻辑错误:get()返回的是模型集合,你需要取单条记录的汇率字段值
  • 集合赋值逻辑错误:push()是追加元素,你需要按「货币名小写 => 汇率值」的结构存为关联结构

修改后代码

public function getByCurrencyName(Request $request)
{
    // 仅获取请求中的currency数组,默认空数组避免参数缺失报错
    $currencies = $request->input('currency', []);
    $result = collect();

    foreach ($currencies as $currencyCode) {
        // 统一转大写查询,避免大小写不匹配找不到数据
        $currency = Currency::where('type', strtoupper($currencyCode))->first();
        if ($currency) {
            // 注意把这里的rate替换为你表中实际存储汇率的字段名
            $result->put(strtolower($currencyCode), $currency->rate);
        }
    }

    // Laravel会自动将集合转为符合你要求的JSON格式返回
    return $result;
}

性能优化版本(推荐)

避免循环查询数据库,减少SQL请求次数,适合查询多个货币的场景:

public function getByCurrencyName(Request $request)
{
    $currencyCodes = collect($request->input('currency', []))
        ->map(fn($code) => strtoupper($code))
        ->toArray();
    // 一次查询所有符合条件的货币
    $currencies = Currency::whereIn('type', $currencyCodes)->get();

    $result = $currencies->mapWithKeys(function ($currency) {
        return [strtolower($currency->type) => $currency->rate];
    });

    return $result;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:39:03