阅读 115

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

这篇文章主要介绍了yii2.0框架多模型操作,结合实例形式分析了Yii2.0多模型添加、修改及删除具体实现技巧,需要的朋友可以参考下

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

控制器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?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模型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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() ?>



文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐