如何在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;
...
官方文件: