将新属性动态添加到Yii2框架中的现有模型对象
在Yii2框架中,是否可以将新属性动态添加到从数据库检索的现有对象中 范例将新属性动态添加到Yii2框架中的现有模型对象,yii2,Yii2,在Yii2框架中,是否可以将新属性动态添加到从数据库检索的现有对象中 范例 //Retrieve from $result $result = Result::findone(1); //Add dynamic attribute to the object say 'result' $result->attributes = array('attempt' => 1); 如果不可能,请建议另一种最佳实施方法 最后,我将把结果转换为json对象。在我的应用程序中,在行为代码块中,我
//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,
],
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',
];
}
...
{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}}
您可以在模型中添加并定义一个公共变量,该变量将动态属性存储为关联数组。它看起来像这样:
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
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',
];
}
...
{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}}
…在您的操作中,将一些动态值传递给您的模型,并将所有内容作为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:
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
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',
];
}
...
{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}}
它正在工作。是否可以不在模型类中声明fields函数。不幸的是,如果使用ActiveRecord,这是不可能的。