<bdo id='y7rMa'></bdo><ul id='y7rMa'></ul>

      <legend id='y7rMa'><style id='y7rMa'><dir id='y7rMa'><q id='y7rMa'></q></dir></style></legend>

    1. <tfoot id='y7rMa'></tfoot>
      1. <i id='y7rMa'><tr id='y7rMa'><dt id='y7rMa'><q id='y7rMa'><span id='y7rMa'><b id='y7rMa'><form id='y7rMa'><ins id='y7rMa'></ins><ul id='y7rMa'></ul><sub id='y7rMa'></sub></form><legend id='y7rMa'></legend><bdo id='y7rMa'><pre id='y7rMa'><center id='y7rMa'></center></pre></bdo></b><th id='y7rMa'></th></span></q></dt></tr></i><div id='y7rMa'><tfoot id='y7rMa'></tfoot><dl id='y7rMa'><fieldset id='y7rMa'></fieldset></dl></div>
      2. <small id='y7rMa'></small><noframes id='y7rMa'>

        模型->save() 在 Yii2 中不起作用

        时间:2023-10-16
      3. <legend id='siK2O'><style id='siK2O'><dir id='siK2O'><q id='siK2O'></q></dir></style></legend>

          <i id='siK2O'><tr id='siK2O'><dt id='siK2O'><q id='siK2O'><span id='siK2O'><b id='siK2O'><form id='siK2O'><ins id='siK2O'></ins><ul id='siK2O'></ul><sub id='siK2O'></sub></form><legend id='siK2O'></legend><bdo id='siK2O'><pre id='siK2O'><center id='siK2O'></center></pre></bdo></b><th id='siK2O'></th></span></q></dt></tr></i><div id='siK2O'><tfoot id='siK2O'></tfoot><dl id='siK2O'><fieldset id='siK2O'></fieldset></dl></div>
            <bdo id='siK2O'></bdo><ul id='siK2O'></ul>
              <tbody id='siK2O'></tbody>

                  <small id='siK2O'></small><noframes id='siK2O'>

                • <tfoot id='siK2O'></tfoot>
                • 本文介绍了模型->save() 在 Yii2 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  Previously, I was not using $model->save() function for inserting or updating any data. I was simply using createCommand() to execute query and it was working successfully. But, my team members asked me to avoid createCommand() and use $model->save();

                  Now, I started cleaning my code and problem is $model->save(); not working for me. I don't know where i did mistake.

                  UsersController.php (Controller)

                  <?php
                  namespace appmodulesuserscontrollers;
                  use Yii;
                  use yiiwebNotFoundHttpException;
                  use yiifiltersVerbFilter;
                  use yiiswiftmailerMailer;
                  use yiifiltersAccessControl;
                  use yiiwebResponse;
                  use yiiwidgetsActiveForm;
                  use appmodulesusersmodelsUsers;
                  use appcontrollersCommonController;
                  
                  class UsersController extends CommonController 
                  {
                      .
                      .
                  
                      public function actionRegister() {
                      $model = new Users();
                  
                          // For Ajax Email Exist Validation
                     if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
                       Yii::$app->response->format = Response::FORMAT_JSON;
                       return ActiveForm::validate($model);
                     } 
                  
                     else if ($model->load(Yii::$app->request->post())) {
                        $post = Yii::$app->request->post('Users');
                        $CheckExistingUser = $model->findOne(['email' => $post['email']]);
                  
                        // Ok. Email Doesn't Exist
                        if(!$CheckExistingUser) {
                  
                          $auth_key = $model->getConfirmationLink();
                          $password = md5($post['password']);
                          $registration_ip = Yii::$app->getRequest()->getUserIP();
                          $created_at = date('Y-m-d h:i:s');
                  
                          $model->auth_key = $auth_key;
                          $model->password = $password;
                          $model->registration_ip = $registration_ip;
                          $model->created_at = $created_at;
                  
                          if($model->save()) {
                            print_r("asd");
                          }
                  
                        }
                  
                      } 
                      }
                      .
                      .
                  }
                  

                  Everything OK in this except $model->save(); Not printing 'asd' as i echoed it.

                  And, if i write

                  else if ($model->load(Yii::$app->request->post() && $model->validate()) {
                  
                  }
                  

                  It's not entering to this if condition.

                  And, if i write

                  if($model->save(false)) {
                      print_r("asd");
                  }
                  

                  It insert NULL to all columns and print 'asd'

                  Users.php (model)

                  <?php
                  
                  namespace appmodulesusersmodels;
                  
                  use Yii;
                  use yiiaseModel;
                  use yiidbActiveRecord;
                  use yiihelpersSecurity;
                  use yiiwebIdentityInterface;
                  use appmodulesusersmodelsUserType;
                  
                  class Users extends ActiveRecord implements IdentityInterface 
                  {
                  
                    public $id;
                    public $first_name;
                    public $last_name;
                    public $email;
                    public $password;
                    public $rememberMe;
                    public $confirm_password;
                    public $user_type;
                    public $company_name;
                    public $status;
                    public $auth_key;
                    public $confirmed_at;
                    public $registration_ip;
                    public $verify_code;
                    public $created_at;
                    public $updated_at;
                    public $_user = false;
                  
                    public static function tableName() {
                      return 'users';
                    }
                  
                    public function rules() {
                      return [
                        //First Name
                        'FirstNameLength' => ['first_name', 'string', 'min' => 3, 'max' => 255],
                        'FirstNameTrim' => ['first_name', 'filter', 'filter' => 'trim'],
                        'FirstNameRequired' => ['first_name', 'required'],
                        //Last Name
                        'LastNameLength' => ['last_name', 'string', 'min' => 3, 'max' => 255],
                        'LastNameTrim' => ['last_name', 'filter', 'filter' => 'trim'],
                        'LastNameRequired' => ['last_name', 'required'],
                        //Email ID
                        'emailTrim' => ['email', 'filter', 'filter' => 'trim'],
                        'emailRequired' => ['email', 'required'],
                        'emailPattern' => ['email', 'email'],
                        'emailUnique' => ['email', 'unique', 'message' => 'Email already exists!'],
                        //Password
                        'passwordRequired' => ['password', 'required'],
                        'passwordLength' => ['password', 'string', 'min' => 6],
                        //Confirm Password
                        'ConfirmPasswordRequired' => ['confirm_password', 'required'],
                        'ConfirmPasswordLength' => ['confirm_password', 'string', 'min' => 6],
                        ['confirm_password', 'compare', 'compareAttribute' => 'password'],
                        //Admin Type
                        ['user_type', 'required'],
                        //company_name
                        ['company_name', 'required', 'when' => function($model) {
                            return ($model->user_type == 2 ? true : false);
                          }, 'whenClient' => "function (attribute, value) {
                            return $('input[type="radio"][name="Users[user_type]"]:checked').val() == 2;
                        }"], #'enableClientValidation' => false
                        //Captcha
                        ['verify_code', 'captcha'],
                  
                        [['auth_key','registration_ip','created_at'],'safe'] 
                      ];
                    }
                  
                    public function attributeLabels() {
                      return [
                        'id' => 'ID',
                        'first_name' => 'First Name',
                        'last_name' => 'Last Name',
                        'email' => 'Email',
                        'password' => 'Password',
                        'user_type' => 'User Type',
                        'company_name' => 'Company Name',
                        'status' => 'Status',
                        'auth_key' => 'Auth Key',
                        'confirmed_at' => 'Confirmed At',
                        'registration_ip' => 'Registration Ip',
                        'confirm_id' => 'Confirm ID',
                        'created_at' => 'Created At',
                        'updated_at' => 'Updated At',
                        'verify_code' => 'Verification Code',
                      ];
                    }
                  
                    //custom methods
                    public static function findIdentity($id) {
                      return static::findOne($id);
                    }
                  
                    public static function instantiate($row) {
                      return new static($row);
                    }
                  
                    public static function findIdentityByAccessToken($token, $type = null) {
                      throw new NotSupportedException('Method "' . __CLASS__ . '::' . __METHOD__ . '" is not implemented.');
                    }
                  
                    public function getId() {
                      return $this->id;
                    }
                  
                    public function getAuthKey() {
                      return $this->auth_key;
                    }
                  
                    public function validateAuthKey($authKey) {
                      return $this->auth_key === $auth_key;
                    }
                  
                    public function validatePassword($password) {
                      return $this->password === $password;
                    }
                  
                    public function getFirstName() {
                      return $this->first_name;
                    }
                  
                    public function getLastName() {
                      return $this->last_name;
                    }
                  
                    public function getEmail() {
                      return $this->email;
                    }
                  
                    public function getCompanyName() {
                      return $this->company_name;
                    }
                  
                    public function getUserType() {
                      return $this->user_type;
                    }
                  
                    public function getStatus() {
                      return $this->status;
                    }
                  
                    public function getUserTypeValue() {
                      $UserType = $this->user_type;
                      $UserTypeValue = UserType::find()->select(['type'])->where(['id' => $UserType])->one();
                      return $UserTypeValue['type'];
                    }
                  
                    public function getCreatedAtDate() {
                      $CreatedAtDate = $this->created_at;
                      $CreatedAtDate = date('d-m-Y h:i:s A', strtotime($CreatedAtDate));
                      return $CreatedAtDate;
                    }
                  
                    public function getLastUpdatedDate() {
                      $UpdatedDate = $this->updated_at;
                      if ($UpdatedDate != 0) {
                        $UpdatedDate = date('d-m-Y h:i:s A', strtotime($UpdatedDate));
                        return $UpdatedDate;
                      } else {
                        return '';
                      }
                    }
                  
                    public function register() {
                      if ($this->validate()) {
                        return true;
                      }
                      return false;
                    }
                  
                    public static function findByEmailAndPassword($email, $password) {
                      $password = md5($password);
                      $model = Yii::$app->db->createCommand("SELECT * FROM users WHERE email ='{$email}' AND password='{$password}' AND status=1");
                      $users = $model->queryOne();
                      if (!empty($users)) {
                        return new Users($users);
                      } else {
                        return false;
                      }
                    }
                  
                    public static function getConfirmationLink() {
                      $characters = 'abcedefghijklmnopqrstuvwxyzzyxwvutsrqponmlk';
                      $confirmLinkID = '';
                      for ($i = 0; $i < 10; $i++) {
                        $confirmLinkID .= $characters[rand(0, strlen($characters) - 1)];
                      }
                      return $confirmLinkID = md5($confirmLinkID);
                    }
                  
                  }
                  

                  Any help is appreciable. Please Help me.

                  解决方案

                  It could be a problem related with your validation rules.

                  Try, as a test, to save the model without any validation in this way:

                  $model->save(false);
                  

                  If the model is saved you have conflict with your validation rules. Try selectively removing your validation rule(s) to find the validation conflict.

                  If you have redefined the value present in active record you don't assign the value to the var for db but for this new var and then are not save.

                  Try removing the duplicated var.. (only the vars non mapped to db should be declared here.)

                  这篇关于模型->save() 在 Yii2 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  上一篇:如何将参数从控制器传递到 YII2 中的布局 下一篇:Yii2 前后端链接(高级模板)

                  相关文章

                    <bdo id='ArjrK'></bdo><ul id='ArjrK'></ul>

                  <small id='ArjrK'></small><noframes id='ArjrK'>

                  <tfoot id='ArjrK'></tfoot><legend id='ArjrK'><style id='ArjrK'><dir id='ArjrK'><q id='ArjrK'></q></dir></style></legend>

                  <i id='ArjrK'><tr id='ArjrK'><dt id='ArjrK'><q id='ArjrK'><span id='ArjrK'><b id='ArjrK'><form id='ArjrK'><ins id='ArjrK'></ins><ul id='ArjrK'></ul><sub id='ArjrK'></sub></form><legend id='ArjrK'></legend><bdo id='ArjrK'><pre id='ArjrK'><center id='ArjrK'></center></pre></bdo></b><th id='ArjrK'></th></span></q></dt></tr></i><div id='ArjrK'><tfoot id='ArjrK'></tfoot><dl id='ArjrK'><fieldset id='ArjrK'></fieldset></dl></div>