当前位置:首页 > CMS教程 > 其它CMS > 列表

yii2.0框架多模型操作示例【添加/修改/删除】

发布:smiling 来源: PHP粉丝网  添加日期:2022-02-27 10:18:07 浏览: 评论:0 

本文实例讲述了yii2.0框架多模型操作,分享给大家供大家参考,具体如下:

控制器:

  1. <?php 
  2.    
  3. namespace app\controllers; 
  4.    
  5. use Yii; 
  6. use yii\web\Controller; 
  7. use yii\base\Model; 
  8. use app\models\shopUsers; 
  9. use app\models\shopLeagueInfo; 
  10. use yii\web\NotAcceptableHttpException; 
  11.    
  12. class UserController extends Controller 
  13. { 
  14.   public $layout = 'shopUser'; 
  15.   public function actionSave($id) 
  16.   { 
  17.     $user = shopUsers::find()->where(['id' => $id])->one(); 
  18.     if (!$user) { 
  19.       throw new NotAcceptableHttpException('没有找到用户信息'); 
  20.     } 
  21.    
  22.     $league = shopLeagueInfo::findOne($user->league_id); 
  23.     if (!$league) { 
  24.       throw new NotAcceptableHttpException('没有找到加盟商信息'); 
  25.     } 
  26.    
  27.     //model设置 
  28.     $user->scenario = 'update'; 
  29.     $league->scenario = 'update'; 
  30.    
  31.     if ($user->load(\Yii::$app->request->post()) && $league->load(\Yii::$app->request->post())) { 
  32.       $isValid = $user->validate(); 
  33.       $isValid = $league->validate() && $isValid; 
  34.    
  35.       if ($isValid) { 
  36.         $user->save(false); 
  37.         $league->save(false); 
  38.         return $this->redirect(['user/save','id' => $id]); 
  39.       } 
  40.     } 
  41.    
  42.     return $this->render('save',['user' => $user,'league' => $league]); 
  43.   } 
  44. } 

model模型:

  1. <?php 
  2.    
  3. namespace app\models; 
  4.    
  5. use yii\db\ActiveRecord; 
  6.    
  7. class shopLeagueInfo extends ActiveRecord 
  8. { 
  9.   public function rules() 
  10.   { 
  11.     return [['user_real_name'],'required']; 
  12.   } 
  13.    
  14.   public function table() 
  15.   { 
  16.     // 
  17.   } 
  18.    
  19.   public function scenarios() 
  20.   { 
  21.     return [ 
  22.       'update' => ['user_phone'],//修改操作,值为表字段 
  23.     ]; 
  24.   } 
  25. } 

其他表同上。

views视图

  1. <?php 
  2. use yii\helpers\Html; 
  3. use yii\widgets\ActiveForm; 
  4.    
  5. $model = new app\models\saveForm(); 
  6. $form = ActiveForm::begin([ 
  7.   'id' => 'save-form', 
  8.   'options' => ['class' => 'form-horizontal'], 
  9. ]) 
  10. ?> 
  11.    
  12. <?= $form->field($user,'user_real_name')->input('user_real_name') ?> 
  13. <?= $form->field($league,'user_phone')->input('user_phone') ?> 
  14.    
  15. <button>更新</button> 
  16. <?php ActiveForm::end() ?>

Tags: yii2.0多模型 yii2.0添加

分享到: