2017-07-07 799 views
1

在Yii2框架中,是否可以将新属性动态添加到从数据库检索的现有对象?向Yii2框架中的现有模型对象动态添加新属性

//Retrieve from $result 
$result = Result::findone(1); 
//Add dynamic attribute to the object say 'result' 
$result->attributes = array('attempt' => 1); 

如果是不可能的,请建议来实现它的替代最佳方法。

最后我会将结果转换为json对象。在我的应用程序,在行为的代码块,我用这样的:

'formats' => [ 
       'application/json' => Response::FORMAT_JSON, 
      ], 

回答

3

您可以添加定义模型内的公共变量,将存储动态属性的关联数组。它会是这个样子:

class Result extends \yii\db\ActiveRecord implements Arrayable 
{ 
    public $dynamic; 

    // Implementation of Arrayable fields() method, for JSON 
    public function fields() 
    { 
     return [ 
      'id' => 'id', 
      'created_at' => 'created_at', 
      // other attributes... 
      'dynamic' => 'dynamic', 
     ]; 
    } 
    ... 

..in你的行动通过一些动态值到模型中,并返回一切,JSON:

public function actionJson() 
{ 
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; 

    $model = Result::findOne(1); 
    $model->dynamic = [ 
     'field1' => 'value1', 
     'field2' => 2, 
     'field3' => 3.33, 
    ]; 

    return $model; 
} 

在结果你会得到JSON是这样的:

{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}} 
+0

它正在工作。是否有可能没有在模型类中声明字段功能。 –

+0

不幸的是,如果你使用ActiveRecord,这是不可能的。 –