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}
如果有更好的方式,不吝赐教~
这种不存在时,就应该返回
null
,而不是这样做。如果有缺省值的需要,那可以在返回的时候包装一下,比如 API Resouce
楼上说的对,对于空对象这种数据,建议返回
null