在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,
],
答案 0 :(得分: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',
];
}
...
..在您的操作中将一些动态值传递给您的模型,并将所有内容返回为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}}