2016-10-27 4 views
0

私のLaravel Appでは、アンケートには多くの投票オプションがあります。私は単純に実行することにより、これらのオプションのコレクションを作成することができますLaravelからのKey/Valueペアの分離関係

$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という列があります。上記のコレクションをとり、responsesのキーと値のペアを分離する必要があります。

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

only()収集方法は、私が必要とするまさにんが、私は雄弁モデルで作業するとき、クエリを構築する方法を見つけ出すことはできません。

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

responses値ので、空のコレクションを返します。 PollOptionオブジェクト内にネストされています。

私もflatten()を試しましたが、このシナリオでは効果がないようです。

Eloquentモデルコレクション内で単一のキーと値のペアを返す簡単な方法はありますか?

答えて

0

コレクション内の複数の値に同じキーを割り当てることは実際にはできません。私はこれを知っていましたが、私は問題を適切に考えていませんでした。

将来のdevsの場合:pluck()メソッドは、引き抜きたい値とキーに割り当てられた値の2つの引数をとります。最終的に私はそれが何をする必要があるかやった

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

:このようなものになり

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

:上記のシナリオを使用して、私は書くことができました。 Amit GuptaのmapWithKeys()の回答も正しいですし、同じ場所に着陸します。