laravel框架response->json响应的json数据被转换为数组,用户端期望得到jsonObject

表 topic: 
    id, title, category_id, content,crated_at,updated_at
表 category:
    id, name,crated_at,updated_at

问题如下

响应:

    public static function success($data = [], string $msg = 'OK') : JsonResponse
    {
         $response = new static();
         $response->msg = $msg;
         $response->data = $data;
         $response->code = ResponseEnum::RETURN_SUCCESS;
         return response()->json($response);
    }

查询:

$topics = Topic::with([
            'category' => function ($query) {
                $query->select(['id', 'name']);
        }])
        ->where(['id' => $id)
        ->first();

关联关系:

# Models/Topic.php
public function category()
{
  return $this->belongsTo(Category::class, 'category_id', 'id')->withDefault(new \stdClass());
}

当 topic 表 category_id 的值为0时,期望 topic.category = {} ,实际上是 []

目前的解决方法

将belongsTo该为hasOne的方式

# Models/Topic.php
public function category()
{
  return $this->hasOne(Category::class, 'id', 'category_id')->withDefault(new \stdClass());
}

可以得到 topic.category = {“id”:0}

如果有更好的方式,不吝赐教~

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2

这种不存在时,就应该返回 null,而不是这样做。

如果有缺省值的需要,那可以在返回的时候包装一下,比如 API Resouce

1年前 评论
随波逐流

楼上说的对,对于空对象这种数据,建议返回 null

1年前 评论

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