首页 > 解决方案 > 查询时乘以 JSON 文件中的动态值

问题描述

我有一个模型以本地货币保存它的价格,并且我将所有货币详细信息存储json在数据库中的数组城堡列字段中。

我的栏目fee

{
  "payment_term": "Monthly",
  "min_fee": 1548,
  "max_fee": 6250,
  "currency": "EUR",
  "fee_details": null
}

我正在使用 cron 作业每天下载货币汇率 json,这样我就可以在 webapp 中使用它。

rates.json

{
    "eur": {
        "code": "EUR",
        "alphaCode": "EUR",
        "numericCode": "978",
        "name": "Euro",
        "rate": 0.85421161576795,
        "date": "Mon, 23 Aug 2021 23:55:01 GMT",
        "inverseRate": 1.1706701027485
    },
    "gbp": {
        "code": "GBP",
        "alphaCode": "GBP",
        "numericCode": "826",
        "name": "U.K. Pound Sterling",
        "rate": 0.7320321066169,
        "date": "Mon, 23 Aug 2021 23:55:01 GMT",
        "inverseRate": 1.3660603011274
    }
]

我的默认货币是USD,我正在根据复选框支持的特定货币范围过滤我的数据

<li>
   <input id="pr-1" class="checkbox-custom" name="pr-1" type="checkbox" wire:model="fee" value="1">
   <label for="pr-1" class="checkbox-custom-label">Up to $5</label>
</li>
<li>
   <input id="pr-2" class="checkbox-custom" name="pr-2" type="checkbox" wire:model="fee" value="2">
   <label for="pr-2" class="checkbox-custom-label">$5 - $10</label>
</li>

我的查询

 $this->teachers = User::where('user_type','tutor')
    ->orderBy('created_at','desc')
    ->whereHas('Teacher', function($query) {
        $query->when($this->fee, function($query) {
            // get currency rates

            foreach ($this->fee as $fee_ind) {
               
               // if first range
                if ($fee_ind == '1') {
                    $min_price = 0;
                    $max_price = null;

                    // $this->rates has the decoded values from rates.json
                    
                    foreach ($this->rates as $key => $value) {
                                  
                                               
                    } 

                }
                
            }
            
            // return  $query;
        });
    })
    ->paginate(15);

有没有办法在usd循环内计算本地化价格,还是我必须创建一个带有汇率的货币表才能实现这一点?任何帮助将不胜感激。

编辑:更新 json 文件的读取

// calculate the rates
$url = storage_path('/seeds/rates_daily.json');        
$json_data = file_get_contents($url);
$this->rates = json_decode($json_data, true); 

标签: phplaraveleloquent

解决方案


推荐阅读