I have this php code, framework yii2

public function getCourse($id) { $data = PriceType::find() ->select('course') ->from('price_type') ->where(['id' => $id]) ->one(); return $data->course; } 

In this method sql query, there is a loop

 $data = PriceType::getCourse($model->price_type_id); if($model->price_type_id == 1) $model->price_usd = ($model->price*$data); elseif ($model->price_type_id == 2) $model->price_usd = ($model->price/$data); elseif ($model->price_type_id == 3) $model->price_usd = ($model->price/$data); elseif ($model->price_type_id == 4) $model->price_usd = ($model->price/$data); 

If the price_type_id value is equal to the id, then we perform such an operation.

if-elseif must be rewritten into one function. The code works, but you need to work regardless of the number of records in the database.

The database contains the courses and currency names. Those. if you need to add a field, you need to write again if ... How to do differently, according to the normal?

  • What would be the normal in the table with the types of prices you need to put an operation to transfer currencies. When getting the price type, get an expression from the database to prepare the data. - Makarenko_I_V
  • How can this be done? Stored procedures? - Vlad Shkuta
  • Tell us what types of prices you have and depending on how you prepare prices. I will offer you a concrete implementation. I mean to create a field operand and let's say for type 1 assign it * , and for 2,3,4 / and on this field it will be clear with what price what to do. All the cheese bor only in order to convert to local currency? - Makarenko_I_V
  • I have a table price_type - 2 columns 1) Currency (USD, UAH, EUR, RUB) 2) Course in relation to usd (1,26,0.85,65). Website ads, when adding ads user chooses what currency he wants to sell. And for sorting and filtering you need to have a single currency. To do this, in the table add ad. I added the price_usd field and when writing to the database I recalculate the entered values ​​at the usd rate and write to the price_usd. There is operand 1, only division. Just something that immediately wrote multiplication, 10/1 = 10 * 1 - Vlad Shkuta
  • If your $data is the exchange rate to the dollar, then standardize it, so that it indicates how much currency you can buy for one dollar, then always when setting the currency you will need to divide and, when received, multiply regardless of the currency. And also make a separate crown every 10min. will update courses. - Makarenko_I_V

0