如何使用yii2将注册用户保存到数据库中?

问题描述 投票:0回答:1

我尝试通过 api 调用将注册用户保存在数据库中。

所以我有一个模型User.php:

<?php

namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;


class User extends \yii\db\ActiveRecord implements IdentityInterface
{

    const STATUS_DELETED = 0;
    const STATUS_INACTIVE = 9;
    const STATUS_ACTIVE = 10;
 

 
    public function behaviors()
    {
        return [
            TimestampBehavior::class,
        ];
    }

    public static function tableName()
    {
        return '{{%user}}';
    }


    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]],
        ];
    }

}

和一个控制器UserController.php:

<?php
// phpcs:ignoreFile

namespace app\modules\v1\controllers;
use Yii;
use app\models\User;
use yii\rest\ActiveController;
use yii\web\Response;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';


    public function actionSignup()
    {
        $user = new User();
        $user->load(Yii::$app->getRequest()->getBodyParams(), '');
        
        if ($user->save()) {
            Yii::$app->response->statusCode = 201;
            return ['status' => 'success', 'data' => 'User registered successfully'];
        } else {
            Yii::$app->response->statusCode = 400;
            return ['status' => 'error', 'data' => $user->errors];
        }
    }

和 web.php 中的 urlManager 看起来:

 'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' =>  ['class' => 'yii\rest\UrlRule', 'controller' => 'v1/user', 'POST' => 'v1/user/signup'],
            
        ]

和数据库架构看起来:

$this->createTable('{{%user}}', [
            'id' => $this->primaryKey(),
            'username' => $this->string()->notNull()->unique(),
            'auth_key' => $this->string(32)->notNull(),
            'verification_token'=> $this->string()->defaultValue(null),
            'password_hash' => $this->string()->notNull(),
            'password_reset_token' => $this->string()->unique(),
            'email' => $this->string()->notNull()->unique(),
            'status' => $this->smallInteger()->notNull()->defaultValue(10),
            'created_at' => $this->integer()->notNull(),
            'updated_at' => $this->integer()->notNull(),
        ]);

但是如果我尝试在邮递员中调用 api 调用:

http://localhost:8080/v1/user/signup 带有 json 对象:

{
    "username": "example_user",
    "password_hash": "example_password",
    "email": "[email protected]" 
}

我收到此错误:

 "name": "Integrity constraint violation",
    "message": "SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"username\" of relation \"user\" violates not-null constraint\nDETAIL:  Failing row contains (3, null, null, null, null, null, 10, 1710925298, 1710925298, null).\nThe SQL being executed was: INSERT INTO \"user\" (\"status\", \"created_at\", \"updated_at\") VALUES (10, 1710925298, 1710925298) RETURNING \"id\"",

问题:如何解决此错误?

php yii2 postman
1个回答
0
投票

您需要为应由

load()
方法填充的所有属性设置验证规则。该方法仅填充被视为“安全”的属性。安全属性是指至少具有一条验证规则的属性。

如果你真的不想验证你的属性,你可以使用

safe
验证器。该验证器不执行任何验证,它仅用于将属性标记为“安全”。

但一般来说,设置适当的验证而不是“接受任何”方法要好得多。

© www.soinside.com 2019 - 2024. All rights reserved.