使用Eloquent of Laravel获取结果时,有没有办法使用主键作为索引?

cyt*_*nny 5 php laravel

假设我在MySQL数据库中有一个这样的表,id为主键.

--------------------
|id | name | score |
--------------------
 1    Alice   77
--------------------
 2    Bob     89
--------------------
 3    Charlie 95
Run Code Online (Sandbox Code Playgroud)

当使用laravel eloquent从表中获取数据时,

$result = TestingTable::get()->toArray();
return $result;
Run Code Online (Sandbox Code Playgroud)

返回结果是这样的:

{
   0: {
      id: 1,
      name: Alice,
      score: 77,
   },
   1: {
      id: 2,
      name: Bob,
      score: 89,
   },
   2: {
      id: 3,
      name: Charlie,
      score: 95,
   }
}
Run Code Online (Sandbox Code Playgroud)

是否有一个函数,以便返回数组如下:

{
   1: {
      name: Alice,
      score: 77,
   },
   2: {
      name: Bob,
      score: 89,
   },
   3: {
      name: Charlie,
      score: 95,
   }
}
Run Code Online (Sandbox Code Playgroud)

换句话说,我有办法将主键作为返回数组的索引吗?

我知道我可以通过循环数据并构建我自己的数组来获得我想要的东西.我知道我可以编写自己的函数并在需要时调用它.我只是想知道在写一个之前是否有Laravel或PHP中的预构建函数.

luk*_*ter 9

你可以用keyBy()它:

$result = TestingTable::get()->keyBy('id')->toArray();
Run Code Online (Sandbox Code Playgroud)