我想使用我的休息应用程序的场景为我的一个动作添加额外的字段。这就是我做的
控制器动作
$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'],
];
}
但它仍然是返回默认字段,没有任何想法发生变化吗?
答案 0 :(得分:2)
我认为场景仅用于在将数据插入表格之前验证数据
场景功能主要用于验证和大量属性分配。但是,您可以将其用于其他目的。例如,您可以根据当前方案以不同方式声明属性标签。
但是如果你想要特定的字段,你应该在模型中使用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