[求助] 基于 Lumen , model 的一个字段为 MySQL JSON 类型,求助如何导出

求助

个人经验: 平常开发基于 python、go,完全没学过 php。

最近,有个需求,修改实现一个 lumen 项目的接口,业务逻辑基本实现了。 但是,model 的一个字段在 mysql 中是 json 类型保存,请求接口的返回消息为 json 字符串,需要把这个字段的返回消息生成标准的 json 对象。 google 了半天,没找到方法(个人完全不熟悉 php )。

求教一下大家,如何把下面的 priceinfo 字段在请求接口返回时,生成标准的 json 对象。

文件:Model.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model as BaseModel;

abstract class Model extends BaseModel
{
    public function __construct(array $attributes = []) {
        parent::__construct($attributes);
    }
}

文件:RefundFlowModel.php

<?php

namespace App\Models;

class RefundFlowModel extends Model
{

    protected $table = 't_refund_flow';

    protected $primaryKey = 'id';

    protected $hidden = array();

    protected $fillable = array(
        'instanceId',
        'productId',
        'ownerUin',
        'providerOwnerUin',
        'deliverType',
        'flags',
        'refundType',
        'orderName',
        'refundOrderName',
        'orderType',
        'priceInfo',                // 此字段在 mysql 里为 json 类型
        'status',
        'deleted',
        'isNotify',
        'reasonId',
        'remark',
        'startTime',
        'endTime',
    );
    protected $jsonColumns = ['priceInfo'];

接口返回消息展示

{
    "Response": {
        "RefundOrderSet": [
            {
                "EndTime": "2019-01-23 10:13:09",
                "InstanceId": "1111111111",
                "OrderName": "222222222222",
                "OrderType": "RENEW",
                "OwnerUin": 3333333333,
                "PriceInfo": "{\"spec\": \"规格一\", \"cycle\": \"1 个月\", \"price\": 100, \"specId\": \"97-008592-ybmbkl\", \"cycleId\": null, \"isTrial\"
: false, \"disprice\": 100, \"goodsNum\": 1, \"maxQuota\": 0, \"timeSpan\": 1, \"timeUnit\": \"m\", \"totalCost\": 100, \"trialDays\": 0, \"unitPrice\": 100, \"tradePriceId\": 0, \"realTotalCost\": 100}",
                "RefundOrderName": "",
                "StartTime": "2019-01-23 10:13:09",
                "Status": 2
            }
        ],
        "RequestId": "",
        "TotalCount": 2
    }
}

求教一下大家,如何把上面的 priceinfo 字段在请求接口返回时,生成标准的 json 对象。

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2
Epona

RefundFlowModel 中 加入

protected $casts = [
    'priceInfo' => 'json',
];

试试

4年前 评论
Shuyi 4年前
Epona (作者) 4年前

@Epona 目前通过以下方式实现了需求了

目前在model上加了

public function getPriceInfoAttribute($value)
    {
        return json_decode($value);
    }

目前在业务逻辑上加了

foreach ($refundInstanceSet as $item) {
                  $item['PriceInfo'] = json_decode(json_encode($item['PriceInfo'], true));
        }
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!