V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
fz420
V2EX  ›  问与答

[求助] 基于 lumen 有一个项目, model 的一个字段为 mysql json 类型,求助如何导出

  •  
  •   fz420 · 2020-01-18 15:58:05 +08:00 · 1040 次点击
    这是一个创建于 1531 天前的主题,其中的信息可能已经有所发展或是发生改变。

    求助

    个人经验: 平常开发基于 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 对象。

    第 1 条附言  ·  2020-01-18 16:48:36 +08:00

    业务逻辑

    
    class DescribeRefundOrderSet extends Controller
    {
        public function __construct()
        {
            parent::__construct();
        }
    
        public function handle()
        {
            $rules = [
                'InstanceId' => 'required|string',   // 实例ID
                'Limit' => 'required|integer|min:0',
                'Offset' => 'required|integer|min:0',
            ];
    
            if (null != ($err = $this->valid($this->request(), $rules)))
            {
                $this->logger->error(sprintf(
                    '%s::%s params check failed. reason is: %s',
                    __CLASS__, __METHOD__, $err));
                return $err;
            }
    
            $params = $this->parameters();
    
            $conds = [
                'instanceId' => $params['InstanceId'],
            ];
    
            $query = RefundFlowModel::query()
                ->select(['ownerUin as OwnerUin', 'instanceId as InstanceId', 'orderName as OrderName', 'refundOrderName as RefundOrderName', 'orderType as OrderType', 'status as Status', 'priceInfo as PriceInfo', 'startTime as StartTime', 'endTime as EndTime'])
                ->where('instanceId', $conds['instanceId']);
    
            // 总数
            $totalCount = $this->totalCount($query);
    
            // 分页
            $this ->pagination($query,
                (int)$this->parameter('Offset'),
                (int)$this->parameter('Limit')
            );
    
            // 查询
            $refundInstanceSet = $query->get();
    
            foreach ($refundInstanceSet as $item) {
                print($item);
            }
    
            return Response::new(array(
                'RefundOrderSet'=>$refundInstanceSet,
                'TotalCount'=>$totalCount,
            ));
    
        }
    
    }
    
    
    
    
    第 2 条附言  ·  2020-01-18 17:41:47 +08:00

    尝试过的方法

    1. 添加 casts属性
     protected $casts = [
            'priceInfo' => 'array',
        ];
    
    1. 添加访问器
     public function getPriceInfoAttribute($value)
        {
            return json_decode($value);
        }
    
    
    
    1. 添加json_decode
    
    $refundInstanceSet = $query->get();
            //$refundInstanceSet['PriceInfo']=json_decode($refundInstanceSet['PriceInfo'],true);
            //$refundInstanceSet['priceInfo']=json_decode($refundInstanceSet['priceInfo'],true);
            //$refundInstanceSet[PriceInfo]=json_decode($refundInstanceSet[PriceInfo],true);
    
    
    

    以上方法都没成功

    第 3 条附言  ·  2020-01-18 18:12:33 +08:00

    解决方案

    目前,逻辑上添加了这段代码, 基本解决问题

     foreach ($refundInstanceSet as $item) {
                #$item['PriceInfo'] = json_decode($item['PriceInfo']);
                $item['PriceInfo'] = json_decode(json_encode($item['PriceInfo'], true));
            }
    
    1 条回复    2020-01-18 16:59:59 +08:00
    FaceBug
        1
    FaceBug  
       2020-01-18 16:59:59 +08:00
    // 查询
    $refundInstanceSet = $query->get();
    $refundInstanceSet[PriceInfo] = json_decode($refundInstanceSet[PriceInfo] ,true);
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3930 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 414ms · UTC 10:25 · PVG 18:25 · LAX 03:25 · JFK 06:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.