【问题标题】:Yii2 - Implement scenarioYii2 - 实现场景
【发布时间】:2017-02-10 13:08:09
【问题描述】:

我对 Yii 场景有一些疑问 (这个概念对我来说很新

如果我有 Post 扩展 Model 的类 并具有以下属性

public $id;
public $title;
public $body;

CONST SCENARIO_SAVE = 'save';
CONST SCENARIO_UPDATE = 'update';

// Code 1
public function rules() {
    return [
            ['id', 'integer'],
            [['title', 'body'], 'string'],
            [['id', 'title', 'body'], 'required']
    ];
}

public function scenarios()
{
    return [
        self::SCENARIO_SAVE => ['id', 'title', 'body'],
        self::SCENARIO_UPDATE => ['title', 'body']
    ];
}

// Code 2
return [
        ['id', 'integer'],
        [['title', 'body'], 'string'],
        [['id', 'title', 'body'], 'required', 'on' => 'save'],
        [['title', 'body'], 'required', 'on' => 'update']
];

代码 1 和 2 是一样的吗?

'id', 'title', ‘body’safe from mass 分配给两个代码还是我应该为代码 1 指定“安全”规则?

【问题讨论】:

    标签: yii yii2 yii2-basic-app


    【解决方案1】:

    代码 1代码 2 不一样。 您需要为每个场景指定所有安全属性

    > `// Code 1
    public function rules() {
        return [
                ['id', 'integer'],
                [['title', 'body'], 'string'],
                [['id', 'title', 'body'], 'required']
        ];
    }`
    

    对于代码 1,所有三个属性 id, title, body 在创建和更新操作期间都是必需的。

    > `// Code 2
    return [
            ['id', 'integer'],
            [['title', 'body'], 'string'],
            [['id', 'title', 'body'], 'required', 'on' => 'save'],
            [['title', 'body'], 'required', 'on' => 'update']
    ];`
    

    对于代码2,如果您使用$model->scenario='save'; 将模型场景设置为save,则需要id, title, body

    当需要$model->scenario='update'titlebody 时。

    这是我们如何设置模型场景的示例。假设是Post 类。

    public function actionMyAction(){
        $model = new Post;
        $model->scenario = 'save';//changing the scenario which you want to use
    
        if ($model->load(\Yii::$app->request->post())){
           // the rest of your code here....
    
            if($model->save(true,$this->scenario)){
              //return true if all the attributes passed the validation rules
            } 
        }
    }
    

    这里有一些其他链接可以帮助您开始使用场景

    http://www.yiiframework.com/doc-2.0/yii-base-model.html#scenarios%28%29-detail http://www.bsourcecode.com/yiiframework2/yii2-0-scenarios/

    【讨论】:

    • 你确定吗?再看我的代码1,我把场景方法放在那里
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多