2016-01-22 55 views
1

我有時候一直困擾着我。我有兩個模型sewalockerloker,這兩個模型是相關的。我有一個表格,需要填寫更衣櫃號碼爲loker_id。當提交表格時,我想loker表中被指定爲'借出'而'不可用'的status。我怎麼做?yii2 - 如何將輸入保存在一個表格中並自動更新另一個表格

這裏是我的sewaController:

<?php 

namespace app\controllers; 

use Yii; 
use app\models\SewaLocker; 
use app\models\sewaSearch; 
use app\models\loker; 
use yii\web\Controller; 
use yii\web\NotFoundHttpException; 
use yii\filters\VerbFilter; 


class SewaController extends Controller 
{ 
public function behaviors() 
{ 
    return [ 
     'verbs' => [ 
      'class' => VerbFilter::className(), 
      'actions' => [ 
       'delete' => ['post'], 
      ], 
     ], 
    ]; 
} 

/** 
* Lists all SewaLocker models. 
* @return mixed 
*/ 
public function actionIndex() 
{ 
    $searchModel = new sewaSearch(); 
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams); 

    return $this->render('index', [ 
     'searchModel' => $searchModel, 
     'dataProvider' => $dataProvider, 
    ]); 
} 

/** 
* Displays a single SewaLocker model. 
* @param integer $id 
* @return mixed 
*/ 
public function actionView($id) 
{ 
    return $this->render('view', [ 
     'model' => $this->findModel($id), 
    ]); 
} 

/** 
* Creates a new SewaLocker model. 
* If creation is successful, the browser will be redirected to the 'view' page. 
* @return mixed 
*/ 
public function actionCreate() 
{ 
    $model = new SewaLocker(); 
    $loker = new loker(); 

    if ($model->load(Yii::$app->request->post()) && $model->save()) { 
     return $this->redirect(['view', 'id' => $model->id_sewa]); 
    } else { 
     return $this->render('create', [ 
      'model' => $model, 
     ]); 
    } 
} 
+0

你想在創建操作中做到這一點? .. – scaisEdge

+0

是的,我想在'SewaController'的'actionCreate()'中做它。 – ishadif

回答

1

在創建你應該做這樣

如果SewaLocker模型保存你那麼可以retrive正確洛克模型ADN更新..

public function actionCreate() 
{ 
    $model = new SewaLocker(); 


    if ($model->load(Yii::$app->request->post()) && $model->save()) { 
     $loker = $this->findLokerModel($model->locker_id); 
     $loker->status ="Loaned not available"; 
     $loker->save(); 

     return $this->redirect(['view', 'id' => $model->id_sewa]); 
    } else { 
     return $this->render('create', [ 
      'model' => $model, 
     ]); 
    } 
} 

protected function findLokerModel($id) 
{ 
    if (($model = Loker::findOne($id)) !== null) { 
     return $model; 
    } else { 
     throw new NotFoundHttpException('The requested page does not exist.'); 
    } 
} 
+0

它說'調用未定義函數app \ controllers \ findLokermodel()'。那麼我錯過了什麼? – ishadif

+0

您在控制器中添加了findLoker模型?最終改變保護在公開測試.. – scaisEdge

+0

是的,我加入我的控制器。沒有什麼改變,它也是這樣說的。 – ishadif

相關問題