yii2.0框架多模型操作示例【添加/修改/删除】
程序员文章站
2022-03-07 13:17:30
本文实例讲述了yii2.0框架多模型操作。分享给大家供大家参考,具体如下:控制器:
本文实例讲述了yii2.0框架多模型操作。分享给大家供大家参考,具体如下:
控制器:
<?php namespace app\controllers; use yii; use yii\web\controller; use yii\base\model; use app\models\shopusers; use app\models\shopleagueinfo; use yii\web\notacceptablehttpexception; class usercontroller extends controller { public $layout = 'shopuser'; public function actionsave($id) { $user = shopusers::find()->where(['id' => $id])->one(); if (!$user) { throw new notacceptablehttpexception('没有找到用户信息'); } $league = shopleagueinfo::findone($user->league_id); if (!$league) { throw new notacceptablehttpexception('没有找到加盟商信息'); } //model设置 $user->scenario = 'update'; $league->scenario = 'update'; if ($user->load(\yii::$app->request->post()) && $league->load(\yii::$app->request->post())) { $isvalid = $user->validate(); $isvalid = $league->validate() && $isvalid; if ($isvalid) { $user->save(false); $league->save(false); return $this->redirect(['user/save','id' => $id]); } } return $this->render('save',['user' => $user,'league' => $league]); } }
model模型:
<?php namespace app\models; use yii\db\activerecord; class shopleagueinfo extends activerecord { public function rules() { return [['user_real_name'],'required']; } public function table() { // } public function scenarios() { return [ 'update' => ['user_phone'],//修改操作,值为表字段 ]; } }
其他表同上。
views视图
<?php use yii\helpers\html; use yii\widgets\activeform; $model = new app\models\saveform(); $form = activeform::begin([ 'id' => 'save-form', 'options' => ['class' => 'form-horizontal'], ]) ?> <?= $form->field($user,'user_real_name')->input('user_real_name') ?> <?= $form->field($league,'user_phone')->input('user_phone') ?> <button>更新</button> <?php activeform::end() ?>
上一篇: Python深度学习pytorch神经网络汇聚层理解
下一篇: JS面试题中深拷贝的实现讲解