Php 从Laravel模型关系中分离键/值对

Php 从Laravel模型关系中分离键/值对,php,laravel,collections,eloquent,Php,Laravel,Collections,Eloquent,在我的Laravel应用程序中,投票有许多投票选项。我可以通过运行以下命令创建这些选项的集合: $result=Poll::find(1)->options()->get() 此查询返回: Collection {#387 ▼ #items: array:6 [▼ 0 => PollOption {#388 ▼ #table: "poll_options" #connection: null #primar

在我的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
  ]
}
collection方法正是我所需要的,但在使用雄辩的模型时,我不知道如何构造查询:

$options = Poll::find(1)->options()->get();
$responses = $options->only('responses');
dd($responses->all());
返回空集合,因为
responses
值嵌套在
PollOption
对象中

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


在一个雄辩的模型集合中,是否有更简单的方法返回单个键/值对?

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

对于未来的开发人员:该方法接受两个参数:您想要获取的值,以及分配给键的第二个值。使用上述场景,我能够编写:

$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
  ]
}
它最终完成了我需要它做的事情。阿米特·古普塔的回答也是正确的,会让你站在同样的位置上