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

Laravel 10 Controller:如何通过名称获取纯数字ID而非数组结构?

解决Laravel中获取纯数字ID而非带键名数组的问题

核心解决方案

根据你的需求,分两种场景处理:

  • 单个分类ID:直接用value('id')获取纯数字ID,这是最简洁的方式:

    $category_id = Category::where('name', $name)->value('id');
    

    也可以先获取模型实例再取ID(适合需要同时用到分类其他字段的场景):

    $category = Category::where('name', $name)->first();
    $category_id = $category?->id; // 用null安全运算符避免分类不存在时报错
    
  • 多个分类ID:如果可能匹配多个分类,用pluck('id')得到纯数字ID数组(比如[6, 8]),查询产品时用whereIn:

    $category_ids = Category::where('name', $name)->pluck('id')->toArray();
    $products = Product::whereIn('category', $category_ids)->get();
    

为什么你的代码会出问题

你之前用get('id')返回的是Eloquent集合对象,结构是[{ "id": 6 }]。当把这个集合传给Product::where('category', $category_id)时,Laravel会自动把集合转成数组去匹配category字段,但你的category字段存的是单个数字ID,自然匹配不到,所以产品结果为空。

修改后的完整代码

public function index(string $name)
{
    $category_id = Category::where('name', $name)->value('id');

    // 处理分类不存在的情况
    if (!$category_id) {
        abort(404, '分类不存在');
    }

    return Inertia::render('Category', [
        'category_id' => $category_id,
        'category' => $name,
        'product' => Product::where('category', $category_id)->get()
    ]);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:46:13