【问题标题】:Yii2 set scenario is not workingYii2 设置场景不起作用
【发布时间】:2017-10-19 11:04:14
【问题描述】:

我想为我的休息应用程序使用场景添加额外的字段。这就是我所做的

控制器动作

$model =(new Job(['scenario' => Job::SCENARIO_MORE]))->findOne(['id'=>$id]);
if ($model){
    return $model;
}


型号代码

const SCENARIO_LESS = 'index';
const SCENARIO_MORE = 'view';

public function scenarios()
{
    return [
        self::SCENARIO_LESS => ['field1', 'field2'],
        self::SCENARIO_MORE => ['field1', 'field2', 'field3'],
    ];
}

但它仍然返回默认字段,没有任何想法发生变化?

【问题讨论】:

    标签: yii2 yii2-advanced-app


    【解决方案1】:

    我认为场景仅用于在将数据插入表之前验证数据

    场景特征主要用于验证和海量属性分配。但是,您可以将其用于其他目的。例如,您可以根据当前场景声明不同的属性标签。

    但是如果你想要特定的字段,你应该在模型中使用fields 方法:

    // explicitly list every field, best used when you want to make sure the changes
    // in your DB table or model attributes do not cause your field changes (to keep API backward compatibility).
    public function fields()
    {
        return [
            // field name is the same as the attribute name
            'id',
    
            // field name is "email", the corresponding attribute name is "email_address"
            'email' => 'email_address',
    
            // field name is "name", its value is defined by a PHP callback
            'name' => function () {
                return $this->first_name . ' ' . $this->last_name;
            },
        ];
    }
    
    // filter out some fields, best used when you want to inherit the parent implementation
    // and blacklist some sensitive fields.
    public function fields()
    {
        $fields = parent::fields();
    
        // remove fields that contain sensitive information
        unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token']);
    
        return $fields;
    }
    

    见:http://www.yiiframework.com/doc-2.0/guide-structure-models.html#fields

    【讨论】:

    • 我可以使用场景过滤 fields() 函数中的字段吗?
    • 你为什么不试一试呢?但我不这么认为。你可以做的是使用toArray() 函数,它会给你一个模型数组,然后使用unset 函数删除特定字段?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    相关资源
    最近更新 更多