以前,我没有使用$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'
用户.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);
}
}
任何帮助都是可观的。请帮我。