douyin7829 2015-12-25 21:33
浏览 114

如何从Db输出原始JSON

I'm using common Yii2 ActiveController REST implementaion:

class ResultController extends ActiveController    
{
    public $modelClass = 'app\models\Result';
    public function actionResultList($id)
    {
        /* @var $modelClass \yii\db\BaseActiveRecord */
        $modelClass = $this->modelClass;

        return new ActiveDataProvider...

It works all good for me, except one feature - I've got some JSON stored in my Result->rawJson model as string. When I'm outputting it through this controller it gets escaped with slashes, and angular on frontend treats it as a string. The question is how to tell serializer not to serialize several model fields and pass them 'as is'.

I found only this dirty hack to do it, i've added afterFind in my model class:

public function afterFind()
{
    $this->rawJson= json_decode($this->rawJson);
}

I'll appreciate any help on this, thanks in advance.

  • 写回答

1条回答 默认 最新

  • dps69208 2015-12-26 11:24
    关注

    I suggest you leave the original attribute untouched and create a new attribute with a getter-setter pair. Assuming that your original attribute is called rawJson:

    public function getProcessedJson()
    {
        return json_decode($this->rawJson);
    }
    
    public function setProcessedJson($value)
    {
        $this->rawJson = json_encode($value);
    }
    

    Then just add processedJson to your fields() method, and you're good to go.

    评论

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线