How to update the child records based on current record

Hi,

I am using Yii2 framework.

I am using XAMPP web server and mysql. I have a table called groupsavingdetails which saves the monthly saving for each month of groups. The ClosingBalance of 1st month will be the OpeningBalance for 2nd month and so on.

I have records for month August, September, October, November and December for year 2017.

I have a situation where updating a record for September involves updating all the records greater than September in the table based on the changes made to each previous record.

If I change some values in some fields and click on Calculate button, then the closing balance will get displayed and the same will get saved into database field. Now before saving this record the closing balance of september should be set to October’s Opening balance and so octobers closing balance will also change based on new october opening balance. And this will continue till records exists.

Meaning if I change values in September record, then the closing balance saved for September should be the opening balance for October record through query and October closing balance will also change. Then this October opening balance and closing balance should be used for November and so on. How to accomplish this code. I have the below code snippet

$groups = Yii::$app->db->createCommand('SELECT * FROM groupsavingdetails where groupsavingdetails.GroupId=:Id and Year>=:year and Month>:month')->bindValues([':Id'=>$model->GroupId,':year'=>$model->Year,':month'=>$model->Month])->queryAll();

$result;
for ( $i = 0; $i <count($groups);$i++) {
    
	
if($i==0)
	{
		$result = $this->findModel($groups[$i]['GroupSavingDetailsId']);
         $groups[$i]['OpeningBalance']= $model->ClosingBalance;
   $groups[$i]['TotalValueofLoanGiven']=$model->TotalValueofLoanGiven;
   $groups[$i]['LoanRepaidUptilNow']=$model->LoanRepaidUptilNow;
   $groups[$i]['TotalValueOfLoanOutstanding']=$model->TotalValueOfLoanOutstanding;

    $result[$i] = $groups[$i];

	$result[$i]->save();
	}  
}
$model->save();