Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Yii2中定义场景?_Yii2 - Fatal编程技术网

如何在Yii2中定义场景?

如何在Yii2中定义场景?,yii2,Yii2,我的模型规则是这样的 public function rules() { return [ [['email','password'], 'required'], [['email'],'unique'], [['status','role_id','created_by', 'updated_by', 'is_deleted'], 'integer'],

我的模型规则是这样的

public function rules()
        {
            return [
                [['email','password'], 'required'],
                [['email'],'unique'],
                [['status','role_id','created_by', 'updated_by', 'is_deleted'], 'integer'],
                [['created_at', 'updated_at'], 'safe'],
                [['first_name', 'last_name', 'email', 'username','location','address','about_me'], 'string', 'max' => 200],
                [['phone'], 'string', 'max' => 100]
            ];
        }

创建新用户时,我需要电子邮件和密码,但在更新过程中,我只需要用户名。如何做到这一点?

首先,最好将场景作为常量添加到模型中,而不是硬编码字符串,例如:

const SCENARIO_CREATE = 'create';
然后你可以这样使用它:

[['email','password'], 'required', 'on' => self::SCENARIO_CREATE],
另一种方法是在
scenarios()
方法中描述它:

public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios[self::SCENARIO_CREATE] = ['email', 'password'];

    return $scenarios;
}
这样,您需要为每个场景指定所有安全属性

最后,不要忘记在创建新的模型实例之后设置所需的场景

$model = new User;
$model->scenario = User::SCENARIO_CREATE;
...
官方文件: