2017-10-19 113 views
0

我想爲我的其他應用程序添加額外的字段到我的一個動作中。這是我做過什麼

控制器動作Yii2設置場景不起作用

$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'], 
    ]; 
} 

但發生的任何想法還是它返回默認的領域,沒有變化?

回答

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

+0

我可以使用場景中的字段篩選字段()函數? –

+1

你爲什麼不試試看?但我不這麼認爲。你可以做的是使用'toArray()'函數,它會給你一個模型的數組,然後使用'unset'函數去除特定的字段? –