This question may be asked several times but I have seen almost all of them but still unable to get an answer.
The flow is simple. A user has been issued sims
. When sims are issued I am inserting the count of sims against that user in a table called sim_balance
.
Now There is a use-case for SIM Return
. While returning the sim I am updating the above table. As in above image, one can see that total 8 sims have been issued to the same user but with different date time. The code for updating table is below
Sim Return Create
$model = new SimReturn();
$result = 0;
$returned_by = 0;
try{
if (isset($_REQUEST['selected_imsi'])) {
foreach ($_REQUEST['selected_imsi'] as $k => $v) {
$count = $_REQUEST['selected_imsi'];
$result = count($count);
.
.
.
$returned_by = $m->return_by;
.
.
.
if($m->save())
{
// code...
}
}
// below function call is updating the record
SimBalance::update_Record($returned_by,$result);
return $this->redirect(Url::toRoute('/simreturn'));
}catch (Exception $ex)
{
{
return $this->redirect(['index']);
}
}
update_Record
public static function update_Record($user_id,$count){
$sims = SimBalance::find()->where(['user_id'=>$user_id])->one();
$sims->sims_count = $count;
$sims->balance_date_time = date('Y-m-d h:i:s');
return $sims->save();
}
Now, if the SIMs
returned are from the same id
then the record is updated perfectly.
But when I try to return the SIM from different id
, let say I have returned 2
sims from id 1
and 2
sims from id 2
so as they both are for same user_id
so both the sims_count
should be updated. But it's just updating the record for id 1
.
Update 1
As per suggestion is given, now I am using update()
by looking into this link.
public static function update_Record($user_id,$count){
$sims = SimBalance::find()->where(['user_id'=>$user_id])->all();
foreach ($sims as $sim)
{
$model = SimBalance::find()->where(['id'=>$sim->id])->one();
$model->sims_count = $count;
$model->balance_date_time = date('Y-m-d h:i:s');
return $model->save();
}
}
But still, it's not working for me, else it places an additional count.
How can I update the record simultaneously for both the ids
?
Any help would be highly appreciated.
The problem here is that you're returning $model->update(). This means that the foreach will exit in the first loop.
Use instead:
The problem is that you need to have a single record against the user in the
sim_balance
table as you won't be able to track which row to decrement against the given sims, for instance you are getting 2 sims with id1
and2
which belong to the same user now how will you determine that you have decrement-only one of those 2 records or both of them , keep the counter in one single record against the user and decrement it by determining the sims belong to that user