yii2 - 如何以一种形式保存输入并自动更新另一个表

时间:2016-01-22 15:01:28

标签: php activerecord yii2 yii2-basic-app

我有条件一直困扰着我。我有两个模型sewalockerloker,这两个模型是相关的。我在sewalockers中有一个表格,需要填充储物柜号码loker_id。提交表单时,我希望status选定的loker_id分配为'借出'没有'可用'在loker表格中的任何内容。我该怎么做?

这是我的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,
        ]);
    }
}

1 个答案:

答案 0 :(得分:1)

在创建中你应该这样做

如果保存了SewaLocker模型,那么您可以检索正确的loker模型和更新..

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.');
    }
}