【发布时间】:2018-09-13 18:17:36
【问题描述】:
我用 Yii2 框架制作了一个 REST 控制器。当我尝试通过ActiveRecord 模型从我的数据库中检索记录时,JsonFormatter 只给我真实的属性。如何配置JsonFormatter 给我也公共变量?
这是我的代码:
控制器
class MyController extends yii\rest\ActiveController
{
...
public function actionView($id)
{
$struct = \common\models\Struct::find()->where(['id' => '285'])->One();
if ($struct) {
return $struct;
}
return false;
}
}
型号
/**
* property string $id;
* property string $name;
*/
class Struct extends \yii\db\ActiveRecord
{
public $test;
...
public function afterFind()
{
parent::afterFind();
$this->test = 'ok';
}
}
请求结果
{"id":1,"name": "ciccio"}
但如果我用print_r() 打印变量,我就有了所有对象
\app\models\Struct object
(
[test] => ok
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[id] => 1
[name] => ciccio
)
)
如何在不向我的数据库表中添加空字段的情况下获取变量 test 属性?
【问题讨论】:
标签: rest activerecord yii2