You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决通过getById获取分类数据返回Null的问题?

问题:通过categoryById获取分类数据返回Null的排查思路

我在编写测试用例,验证通过categoryById方法获取分类数据的正确性,但接口返回结果为Null。问题截图显示接口返回Null,恳请提供解决思路。

相关代码

CategoryController(PHP)

public function show($id)
{
    try {
        $category = Category::find($id);
        return response()->json([
            'success' => 'OK',
            "categories" => $category,
        ], 200);
    } catch (\Exception $e) {
        return response()->json(['error' => $e->getMessage()], 400);
    }
}

Vue Store(JavaScript)

async getCategoriesById(id) {
    let res = await $axios.get(`/api/categories/${id}`)

    // this.$state.id = res.data[0].id   <-- 此代码也无法正常工作
    
    console.log(res)
},

Categories组件(Vue)

onMounted(async () => {
  getCategoriesById()
})

const getCategoriesById = async () => {
  try {
    await $forumStore.getCategoriesById(route.params.id)
  } catch (error) {
    console.log(error)

  }
}

路由代码(Laravel)

Route::get('/categories/{id}', [CategoryController::class, 'show']);

解决思路

  • 确认数据库中存在对应ID的记录:Category::find($id)返回Null最常见的原因是数据库里没有匹配该ID的分类。可以在控制器中临时添加日志打印请求的ID,同时直接查询数据库验证是否存在该记录。
  • 检查前端参数传递是否正确:在组件的getCategoriesById函数中先打印route.params.id,确认参数是否有效,避免参数丢失或格式错误(比如传入非数字ID)。
  • 优化控制器的异常处理:Category::find()不会因记录不存在抛出异常,改用Category::findOrFail($id),这样当记录不存在时会自动抛出ModelNotFoundException,进入catch块返回明确的错误信息,便于排查问题。
  • 验证前端请求URL是否正确:确认后端路由是否在api路由组中,如果后端路由没有添加api前缀,前端请求的/api/categories/${id}会找不到接口,需要调整请求路径。
  • 检查模型与数据库的映射:确认Category模型的$table属性是否指向正确的数据库表,数据库连接配置是否正常,避免因表名错误或连接问题导致查询失败。
  • 排查前端接口调用的参数:在Vue Store的getCategoriesById方法中先打印传入的id参数,确认参数是否正确传递到请求中。

内容的提问来源于stack exchange,提问作者Justin Moreyl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:13:11