当使用Laravel的Eloquent获得结果时,有没有一种方法可以使用主键作为索引


Is there a way to use primary key as index when getting results using Eloquent of Laravel?

假设我在MySQL数据库中得到了一个这样的表,id是主键。

--------------------
|id | name | score |
--------------------
 1    Alice   77
--------------------
 2    Bob     89
--------------------
 3    Charlie 95

当使用laravel雄辩地从表中获取数据时,

$result = TestingTable::get()->toArray();
return $result;

返回的结果是这样的:

{
   0: {
      id: 1,
      name: Alice,
      score: 77,
   },
   1: {
      id: 2,
      name: Bob,
      score: 89,
   },
   2: {
      id: 3,
      name: Charlie,
      score: 95,
   }
}

有没有一个函数可以使返回数组像:

{
   1: {
      name: Alice,
      score: 77,
   },
   2: {
      name: Bob,
      score: 89,
   },
   3: {
      name: Charlie,
      score: 95,
   }
}

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

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

您可以使用keyBy()

$result = TestingTable::get()->keyBy('id')->toArray();
相关文章: