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() ?>
更多關于Yii相關內容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結》、《php優(yōu)秀開發(fā)框架總結》、《smarty模板入門基礎教程》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數(shù)據庫操作入門教程》及《php常見數(shù)據庫操作技巧匯總》
希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。
- YII2框架中自定義用戶認證模型,完成登陸和注冊操作示例
- Yii2.0框架模型添加/修改/刪除數(shù)據操作示例
- Yii2.0框架模型多表關聯(lián)查詢示例
- Yii中Model(模型)的創(chuàng)建及使用方法
- yii框架表單模型使用及以數(shù)組形式提交表單數(shù)據示例
- PHP YII框架開發(fā)小技巧之模型(models)中rules自定義驗證規(guī)則
- PHP的Yii框架中Model模型的學習教程
- Yii框架數(shù)據模型的驗證規(guī)則rules()被執(zhí)行的方法
- YII動態(tài)模型(動態(tài)表名)支持分析
- Yii框架表單模型和驗證用法
- Yii模型操作之criteria查找數(shù)據庫的方法
- Yii數(shù)據模型中rules類驗證器用法分析
相關文章
PHP 面向對象程序設計(oop)學習筆記(三) - 單例模式和工廠模式
設計模式是一套被反復使用、多數(shù)人知曉的、經過分類編目的、代碼設計經驗的總結。使用設計模式是為了可重用代碼、讓代碼更容易被他人理解、保證代碼可靠性。2014-06-06Yii操作數(shù)據庫實現(xiàn)動態(tài)獲取表名的方法
這篇文章主要介紹了Yii操作數(shù)據庫實現(xiàn)動態(tài)獲取表名的方法,涉及Yii框架針對數(shù)據庫的動態(tài)操作技巧,需要的朋友可以參考下2016-03-03thinkphp中html:list標簽傳遞多個參數(shù)實例
這篇文章主要介紹了thinkphp中html:list標簽傳遞多個參數(shù)的解決方法,在處理參數(shù)傳遞的情況非常具有實用價值,需要的朋友可以參考下2014-10-10CI(Codeigniter)的Setting增強配置類實例
這篇文章主要介紹了Codeigniter的Setting增強配置類,結合實例形式較為詳細的分析了Codeigniter增強配置類的具體實現(xiàn)步驟與相關技巧,需要的朋友可以參考下2016-01-01