I
I
Ivan Lykov2018-06-13 10:01:05
Yii
Ivan Lykov, 2018-06-13 10:01:05

How to write data to database table when data is summarized?

Good afternoon, I have a question. I do not come across such a task so often, but still the task is simple from the point of view of theory ... but I cannot understand how to solve the problem correctly ...
There is a table with values, there are two fields in the table.
5b20beb6ca25a813621565.png
Further I do request in a database for selection. I sum the fields so that I get an integer.

public static function checkMyBonus( $user_id )
    {
      return UserMainPersonalBonus ::find()
                     -> where( [ 'user_id' => $user_id ] )
                     -> select(
                       '
                      SUM(count_events_week) as count_events_week,
                      SUM(count_time_for_conf_room) as count_time_for_conf_room,
                      SUM(count_time_for_massage) as count_time_for_massage,
        '
                     )
                     -> groupBy( 'user_id' )
                     -> all();
    }

But now the task has become, you need to overwrite the values ​​​​of the fields, with one field it’s still okay. Found - given - recorded.
But here there are two fields, for example, fields where the values ​​are 2 and 4. The value 3, for example, came into the request. It is necessary to write down so that 3 would be taken away in the fields. Tobish left 0 and 1
The standard update markup is as follows.
public static function updateMyBonus( $user_id, $count_events_week = NULL, $count_time_for_massage = NULL, $count_time_for_conf_room = NULL )
    {
      $model = UserMainPersonalBonus::findOne( $user_id );

      $old_count_events_week = $model -> count_events_week - $count_events_week;
      $old_count_time_for_massage = $model -> count_time_for_massage - $count_time_for_massage;
      $old_count_time_for_conf_room = $model -> count_time_for_conf_room - $count_time_for_conf_room;

      if( !empty( $count_events_week ) )
      {
        $model -> count_events_week = $old_count_events_week;
      }
      if( !empty( $count_time_for_massage ) )
      {
        $model -> count_time_for_massage = $old_count_time_for_massage;
      }
      if( !empty( $count_time_for_conf_room ) )
      {
        $model -> count_time_for_conf_room = $old_count_time_for_conf_room;
      }
      if( !$model -> save() )
      {
        dd( $model -> errors );
      }
    }

As far as I understand, here you need to give the id of the record, and then give it to the request with id_user. And search for it. Or how else I thought that it could search by the smallest value of the table, if the value is 0, then move on to another record. If there are no values, then tell the user about it ...
I would be glad for any advice ... my head does not cook :((

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Lykov, 2018-06-14
@Jhon_Light

After a couple of hours I came to this conclusion. (This is an example for one field, I have 5 of them, others are similar, we are limited only by imagination)
First, I drew a diagram on a sheet with a pen, then it was a matter of technology.

public static function updateMyBonus( $user_id, $count_events_week = NULL, $count_time_for_massage = NULL, $count_time_for_conf_room = NULL )
    {
      $model = self ::updateBonus( $user_id );
      // Если данные которые пришли в $count_events_week меньше чем в базе.
      // То передаем ее дальше и отнимаем от уже существующего значения в базе
      if( $count_events_week < $model -> count_events_week )
      {
        // Пример 3 - 2 = 1
        // Отнимаем от значений в базе значене $count_events_week
        $old_data_value = $model -> count_events_week - $count_events_week;
        // записываем
        $model -> count_events_week = $old_data_value;
        // сохраняем
        $model -> save();
      }
      // если данные в $count_events_week равны значению которые в базе. Пишем чистый ноль без лишних движений
      elseif($count_events_week == $model -> count_events_week)
      {
        // Пример 3 = 3 пишем ноль
        $model -> count_events_week = 0;
        $model -> save();
      }
      // Если же данные в $count_events_week больше занчения в базе у первого поля
      // То записываем ноль и снова вызываем функцию для вызов новой записи.
      else
      {
        // Для получения разницы отнимаем данные которые пришли в $count_events_week, от того что есть в базе
        //Пример: Пришло 7 В базе 4
        //  7 - 4 = 3 это наша разница
        $remainder = $count_events_week - $model -> count_events_week;
        //записываем ноль в первое поле
        $model -> count_events_week = 0;
        // сохраняем
        if( $model -> save() )
        {
          // Дальше вызываем снова туже самую функцию, но так как мы уже записал ноль в первое поле
          // Оно отдаст второе поле у которо поле не больше нуля
          $next_model = self ::updateBonus( $user_id );
          // Ранее полученую разницу отнимаем от основного значения которое хранит в себе второе поле
          // Пример: 4 - 3 = 1 
          $old_data_value = $next_model -> count_events_week - $remainder;
          // Сохраняем данные
          $next_model -> count_events_week = $old_data_value;
          $next_model -> save();
        }
      }
    }

    // С помощью этой функции мы и обращаемся к полям где значения больше нуля
    protected static function updateBonus( $user_id )
    {
      $row =  self ::find() -> where( [ 'user_id' => $user_id ] )
                  -> andWhere(['>','count_events_week',0])
              -> orderBy( [ 'date_end' => SORT_ASC] )
 						  -> one();
      return $row;
    }

M
Mykola, 2018-06-13
@iSensetivity

Why not make 1 entry?
Why not pass some additional parameters when updating?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question