繁体   English   中英

将数据更新到相关表yii2

[英]Update data to related tables yii2

我有表USRORGANIZATION

USR表

|ID | ID_APP | NAMA_APP|

组织表

|ID | NAMA |

我试图通过ID(关系)将数据从ORGANIZATION插入USR表(ID_APP和NAMA_APP)。 这是我的代码:

UsersController:

public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if (Yii::$app->request->post()) {
            try {
                $state = true;
                $data = Yii::$app->request->post();
                $transaction = Yii::$app->db->beginTransaction();
                $model->ID_APP = $data['USR']['ID_APP'];
                $model->NAMA_APP = $data['USR']['NAMA_APP'];

                if (!$model->save()) {
                    $ErrorMessage = $model->getErrorMessage($model->getErrors());
                    throw new Exception($ErrorMessage);
                }
                $transaction->commit();
                $message = "Success update Application ";
            } catch (Exception $e) {
                $state = false;
                $transaction->rollback();
                $message = $e->getMessage();
            }
            if ($state) {
                Yii::$app->session->setFlash('successApplication', $message);
                return $this->redirect(['view', 'id' => $model->ID]);
            } else {
                Yii::$app->session->setFlash('errorApplication', $message);
                return $this->render('view', ['id' => $model->ID]);
            }

        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

我的观点 :

<?php $org = \app\models\ORGANIZATION::find()->all(); ?>
                <?= $form->field($model, 'ID_APP')->dropDownList(
                    ArrayHelper::map($org,'ID', 'NAMA'))->label('ID APP') ?> 

我仍然是phpyii2框架的初学者。如何从NAMA( ORGANIZATION )获取NAMA_APP( USR表)?

根据您的假设,假设您发布了ID_APP,并且需要为USR中的单独商店检索NAMA_APP

  // make accessible your ORGANIZAZTION model with use eg: 
  // use common\models\ORGANIZATION;  or  
  use yourapp\models\ORGANIZATION;

  public function actionUpdate($id)
      {
          $model = $this->findModel($id);

          if (Yii::$app->request->post()) {
              try {
                  $state = true;
                  $data = Yii::$app->request->post();
                  $transaction = Yii::$app->db->beginTransaction();
                  $model->ID_APP = $data['USR']['ID_APP'];

                  // then  you can use eg: the  find method 
                  // related to ORGANIZAZTION active record   

                  $modelOrg =  ORGANIZATION::find()->where(['ID_APP']=> $data['USR']['ID_APP'])->one();
                  $model->NAMA_APP =  $modelOrg->NAMA_APP

                  ....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM