0

I have a custom collection I wanted to update a record. I want to do this as below:

foreach ($creditDetails as $Card) { 

        echo $Card->getRedeemAmount();
        $Card->setRedeemAmount(44);
        echo $Card->getRedeemAmount();
        //exit;
        $Card->save();
        exit;

but Card is not getting save. Initially it was working but I don't know what problem has occurred now. Please a suggest solution.

  • Is it working for you? – Rohan Hapani Aug 27 at 6:14
  • yes by loading model it worked – Ajwad Syed Aug 27 at 13:39
2

First of all, you should load your record which you want to update. Then, you can update record like this :

$creditDetailsObject = $this->creditDetailsFactory->create()->load(1); //Load particular data which you want to update
foreach ($creditDetails as $Card) { 
    $creditDetailsObject->setRedeemAmount(44); //set value in object which you want to update
    $creditDetailsObject->save();
}
2

You need to load model while updating data.

code as below:

foreach ($creditDetails as $Card) { 
        $cardModel = $this->cardFactory->create()->load($cardId);
        $cardModel->setRedeemAmount(44);
        $cardModel->save();
}
  • In above code $this->cardFactory is your model factory you need to add dependency in construct
  • $cardId is your table primary key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.