php - 将键/值对与 Laravel 模型关系隔离

标签 php laravel collections eloquent

在我的 Laravel 应用程序中,民意调查有很多民意调查选项。我只需运行以下命令即可创建这些选项的集合:

$result = Poll::find(1)->options()->get();

此查询返回:

Collection {#387 ▼
    #items: array:6 [▼
        0 => PollOption {#388 ▼
          #table: "poll_options"
          #connection: null
          #primaryKey: "id"
          #keyType: "int"
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:8 [▼
            "id" => 1
            "poll_id" => 1
            "option_text" => "Never"
            "responses" => 54
            "is_public" => 0
            "created_at" => null
            "updated_at" => null
            "deleted_at" => null
          ]
          #original: array:8 [▶]
          #relations: []
          #hidden: []
          #visible: []
          #appends: []
          #fillable: []
          #guarded: array:1 [▶]
          #dates: []
          #dateFormat: null
          #casts: []
          #touches: []
          #observables: []
          #with: []
          #morphClass: null
          +exists: true
          +wasRecentlyCreated: false
        }
        1 => PollOption {#389 ▶}
        2 => PollOption {#390 ▶}
        3 => PollOption {#391 ▶}
    ]
}

在我的投票选项中,有一个名为“responses”的列,它返回一个整数。我需要获取上面的集合并隔离响应键/值对。

Collection {#385 ▼
  #items: array:6 [▼
    "responses" => 54
    "responses" => 20
    "responses" => 10
    "responses" => 123
    "responses" => 33
    "responses" => 11
  ]
}

only() collection 方法正是我所需要的,但我无法弄清楚在使用 Eloquent 模型时如何构造查询:

$options = Poll::find(1)->options()->get();
$responses = $options->only('responses');
dd($responses->all());

返回一个空集合,因为 responses 值嵌套在 PollOption 对象中。

我也尝试过flatten() ,但这似乎在这种情况下没有效果。

是否有更简单的方法来返回 Eloquent 模型集合中的单个键/值对?

最佳答案

实际上不可能将同一个键分配给集合中的多个值。我知道这一点,但我没有正确思考问题。

对于 future 的开发人员:pluck()方法接受两个参数:您想要提取的值,以及分配给键的第二个值。使用上面的场景,我能够编写:

$result = $poll->options()->pluck('responses', 'option_text'); //Value and corresponding key

这会导致类似的结果:

Collection {#386 ▼
  #items: array:6 [▼
    "Never" => 54
    "Occasionally" => 21
    "2–3 times a week" => 80
    "4–5 times per week" => 33
    "Daily" => 11
  ]
}

这最终完成了我需要它做的事情。阿米特·古普塔的mapWithKeys()答案也是正确的,并且会让你回到同一个地方。

关于php - 将键/值对与 Laravel 模型关系隔离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40289080/

相关文章:

Laravel:更改队列通知内调用的路由中的应用程序 URL

javascript - Vue.js 使用 post 方法重定向

c# - C# 匿名数组和列表的 Java 等价物?

php - 替换任何正则表达式 php

php - 使 MySQL 字段中的 NULL 值显示为 0/N/A

php - 检查 MySQL 服务器是否能够接受连接

Java LinkedBlockingQueue 实现

php - 如何从 php 运行 html 文件?

Laravel 将模型类作为函数中的参数传递

c# - Hashtable 对象还有用吗?