0
votes

Maybe is not possible but i have in table answers for radio input with id of question and answer like id = 36 , answer = Yes. My code below get all answers

public function getAnswer() {
        return $this->hasMany('App\Answer', 'user_id', 'id')
            ->with('question')
            ->whereHas('question.group', function($query) {
                $query->where('name', 'simple_quesion');
            });
    }

and i have collection which is ok

#items: array:9 [▼
    0 => getAnswer {#400 ▶}
    1 => getAnswer {#401 ▶}
    2 => getAnswer {#402 ▶}

but is any way to get keys and assign with this collection like

#items: array:9 [▼
        35 => getAnswer {#400 ▶}
        37 => getAnswer {#401 ▶}
        42 => getAnswer {#402 ▶}

in this method public function getAnswer() ?

[UPDATE]

full collection

Collection {#396 ▼
  #items: array:9 [▼
    0 => getAnswer {#400 ▼
      #fillable: array:3 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [▼
        "id" => 18
        "user_id" => 11
        "answer_id" => 34
        "answer" => "YES"
      ]
      #original: array:7 [▶]
      #changes: []

And i need key answer_id => 34

#items: array:9 [▼
    34 => getAnswer {#400 ▼
2
Can you please show how a collection item looks ? - Steve
ok i updated with full collection - Wraith
if i understand correctly you want to be able to recover a question and all its answer ? that's it ? - Steve
yes and i would like avoid create another foreach. I would like do this when i am getting this data in method. - Wraith

2 Answers

1
votes

Ok i am so stupid. This is so easy. In blade or controller i can use:

{{ dd($user->getAnswer->pluck('answer', 'answer_id')) }}
0
votes

Try this :

In Answer model, add this :

public function question(){
    return $this->belongsTo("App\Question"); //the column name of the question should be "question_id"
}

in Question model, do :

public function answers(){
    return $this->hasMany("App\Answer"); 
}

And in your controller, where you want to get the question and its answers, you just do:

Question::with('answers')->all(); //assuming you want to get all the questions and their answers

Hope my answer helps!