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}

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

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2

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

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

1年前 评论
随波逐流

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

1年前 评论

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