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

时间:2015-11-17 14:33:19

标签: php yii2 yii2-basic-app yii2-model

以前,我没有使用$model->save()函数来插入或更新任何数据。我只是使用createCommand()来执行查询,它正在成功运行。但是,我的团队成员要求我避免createCommand()并使用$model->save();

现在,我开始清理我的代码,问题$model->save();对我不起作用。我不知道我错在哪里。

UsersController.php (控制器)

<?php
namespace app\modules\users\controllers;
use Yii;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;
use app\modules\users\models\Users;
use app\controllers\CommonController;

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");
        }

      }

    } 
    }
    .
    .
}

除了$model->save();之外,其他所有内容都没问题。当我回复它时,不打印'asd'

而且,如果我写

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

}

它未进入此if状态。

而且,如果我写

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

它向所有列插入NULL并打印'asd'

Users.php (型号)

<?php

namespace app\modules\users\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
use app\modules\users\models\UserType;

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);
  }

}

任何帮助都是值得的。请帮助我。

10 个答案:

答案 0 :(得分:31)

这可能是与验证规则相关的问题。

尝试以此方式保存模型而不进行任何验证:

$model->save(false);

如果模型已保存,则表明您的验证规则存在冲突。尝试有选择地删除验证规则以找到验证冲突。

如果您已重新定义活动记录中存在的值,则不要将该值分配给db的var,但是对于此新var,则不保存。

尝试删除重复的var ..(只应在此处声明未映射到db的vars。)

答案 1 :(得分:9)

我猜$model->load()会返回false,请致电$model->errors查看模特的错误。

$model->load();
$model->validate();
var_dump($model->errors);

答案 2 :(得分:4)

正如@scaisEdge建议的那样,尝试删除用户类中的所有与表相关的字段

class Users extends ActiveRecord implements IdentityInterface 
{
  /* removed because this properties is related in a table's field 
  public $first_name;
  public $last_name;
  public $email;
  public $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_type;
  public $company_name;
  public $status;
  public $auth_key;
  public $confirmed_at;
  public $registration_ip;
  public $verify_code;
  public $created_at;
  public $updated_at;
  */

  // this is properties that not related to users table
  public $rememberMe;
  public $confirm_password;
  public $_user = false;

  public static function tableName() {
    return 'users';
  }

 /* ........... */

}

答案 3 :(得分:1)

你正在为所有员工做正确的事。我想你必须添加一行来确认密码验证

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->confirm_password= md5($post["confirm_password"]);  /// add  this line
        $model->registration_ip = $registration_ip;
        $model->created_at = $created_at;

并且在此条件之后还检查模型属性和错误,如下所示:

if($model->save()) {
          print_r("asd");
        }else{
var_dump($model);exit;}

答案 4 :(得分:1)

另一个解决方案提到$model->save(false);。这只是一个临时的解决方法,您仍然应该找到保存功能无法正常工作的实际原因。

以下是帮助诊断实际问题的其他步骤:

  1. 检查_form输入字段是否具有正确的名称​​和
  2. 检查是否添加了任何下拉功能,然后检查它是否正常工作

答案 5 :(得分:1)

检查模型保存错误,如下所示:

if ($model->save()) {

} else {
  echo "MODEL NOT SAVED";
  print_r($model->getAttributes());
  print_r($model->getErrors());
  exit;
}

答案 6 :(得分:0)

试试这个:

$model->save(false);

如果有效,请检查您的模型规则()和表单规则()(如果有) 有相同的规则。通常原因是表格中的必填字段。

答案 7 :(得分:0)

如果您的表中的列类型是&#34;整数&#34;你的数据是&#34;字符串&#34;您可能会看到错误。您应该检查您的数据类型,然后重试。

我认为您的列类型是整数,您应该编写以下代码:

$model->created_at=time();//1499722038
$model->save(); 

但是您的列类型是字符串,您应该编写以下代码:

$model->created_at=date('d/m/Y');//11/07/2017
$model->save(); 

答案 8 :(得分:0)

还有另一个原因就是没有保存模型 - 你拥有了你的Users类的属性,并且从表单保存之前它的重置为NULL。

所以,如果您设置$ model-&gt; saveAttributes('favorite_book'=&gt; $ model-&gt; favorite_book),但是当时您在类Users public $ favorite_book中声明 - 您将在DB中将此字段设为空

答案 9 :(得分:-1)

在您的模型中,我发现名字,姓氏,电子邮件,密码是必填字段,在控制器中您只是更新或保存

 $model->auth_key = $auth_key;
        $model->password = $password;
        $model->confirm_password= md5($post["confirm_password"]);  /// add  this line
        $model->registration_ip = $registration_ip;
        $model->created_at = $created_at;

但是名字和姓氏和电子邮件ID都是必需的,所以它会抛出验证错误,检查此错误使用

$model->load();
$model->validate();
var_dump($model->errors);

它会显示错误。纠正错误然后模型将得到保存。 您可以使用Scenario或

解决该错误
$model->saveAttributes('favorite_book'=>$model->favorite_book,'favorite_movie'=>$model->favorite_movie);

我希望它会对你有所帮助。