【问题标题】:Is there a way to use primary key as index when getting results using Eloquent of Laravel?使用 Laravel 的 Eloquent 获取结果时,有没有办法使用主键作为索引?
【发布时间】:2015-04-18 01:31:33
【问题描述】:

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

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

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

$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 中是否有预建函数。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以为此使用keyBy():

    $result = TestingTable::get()->keyBy('id')->toArray();
    

    【讨论】:

    • 只是补充一点,返回结果并不完全像我在问题中所说的那样。 id 用作索引,但它也保留在数组中。但这对我来说已经足够了,因此我接受它作为正确答案。
    • 确实如此。如果你想隐藏它,你可以使用模型中的$hidden 属性来做到这一点
    • 如果该列被隐藏,您仍然可以 keyBy 吗?
    • 是的,我想是的... hidden 仅在转换为数组时起作用,并且在您的情况下发生在 keyBy 之后
    猜你喜欢
    • 2013-02-20
    • 2019-05-21
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2023-01-24
    • 2021-04-05
    相关资源
    最近更新 更多