S
S
Sergey Beloventsev2017-10-17 00:35:58
Yii
Sergey Beloventsev, 2017-10-17 00:35:58

How to organize the save?

there is a controller

public function actionSaveSend
 $user=Yii::$app->user->identity;
        $order=Order::findOne(['id'=>$post['id'],'user_id'=>$user->id]);
        if(!empty($order)){
            $bonus=$this->getPrioritiBonus();
            $paysum=round($this->getBonusSum($bonus),5);
            $bonusRu=$this->getBonusRu($order,$bonus);
            $order->points_bonus=$paysum;
            $order->bonus=$bonusRu;
            $order->save();
            $client = new Client();
            $body=json_encode([
                "ref"=>$user->code,
                "key" => Yii::$app->params['pvk'],
                'sum'=>$paysum,
                'order'=>$order->id]);
            $response = $client->post(\Yii::$app->params['url'],$body, Yii::$app->params['headers'])->send();
            if (!$response->isOk)
                Yii::$app->session->setFlash('error',$response->data['message']);
         }

what do i need 1 i need to do something like a transaction but in the following way the order model is saved after that it is sent if the send returns isOk then everything ends with a redirect. But if not everything is fine, you need to display an error and roll back the saves to the database. Here's just how to do it. I understand using Yii::$app->db->beginTransaction() but how?
I am clarifying the question like this, the code will work as a transaction
$transaction=Yii::$app->db->beginTransaction();
            if($order->save()){
                $client = new Client();
                $body=json_encode([
                    "ref"=>$user->affliliateProgramCode->code,
                    "key" => Yii::$app->params['pvk'],
                    'sum'=>$paysum,
                    'orderNumber'=>$order->id]);
                $response = $client->post(\Yii::$app->params['url'],$body, Yii::$app->params['headers'])->send();
                if (!$response->isOk){
                    Yii::$app->session->setFlash('error',$response->data['message']);
                    $transaction->rollBack();
                    return false;
                }
            }
            $transaction->commit();
            return $this->redirect('/cabinet');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-10-17
@Sergalas

Goodnight.
Here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question