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

Laravel多列查询失败问题:高分榜无法同时获取用户名与分数

解决Laravel Eloquent仅返回指定单个字段的问题

嗨,这问题我之前也碰到过!你遇到的核心问题是对Eloquent的get()方法参数用法理解有误~

Laravel的get()方法如果需要指定多个字段,不能像你那样传多个独立参数,而是要把字段名放在一个数组里作为参数传递。你之前写的get('username', 'score')其实Laravel只会识别第一个参数,第二个参数会被忽略,所以只返回了username字段。

正确的写法有两种:

  1. 直接给get()传字段数组:
public function getNames(Request $request) { 
    $usernames = Highscore::orderBy('score', 'DESC')->get(['username', 'score']); 
    return response()->json($usernames); 
}
  1. 先用select()指定字段,再调用get():
public function getNames(Request $request) { 
    $usernames = Highscore::orderBy('score', 'DESC')->select('username', 'score')->get(); 
    return response()->json($usernames); 
}

额外排查点:

如果改了之后还是拿不到score字段,记得检查你的Highscore模型里有没有设置$hidden属性把score字段隐藏了,比如:

// 模型里如果有这个,score会被自动隐藏
protected $hidden = ['score'];

要是有的话,把score从$hidden里移除,或者设置$visible属性明确指定允许返回的字段:

protected $visible = ['username', 'score'];

这样调整之后,应该就能同时返回用户名和分数啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:11:54