首页 > 解决方案 > Laravel 为嵌套集合添加变量

问题描述

我想将变量添加到集合内的每个集合对象。这里的 JSON 响应是这样的:

         {
         "id": 16,
          "survey_id": "8",
          "title": "How are you?",
          "created_at": "2020-02-06 04:21:44",
          "updated_at": "2020-02-06 04:21:44",
              "answers": [

在这里,我想为每个答案添加变量

{
            "id": 52,
            "question_id": "16",
            "text": "VERY GOOD",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "4",
            "responded": 2
        },
        {
            "id": 53,
            "question_id": "16",
            "text": "OK",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "4",
            "responded": 2
        },
        {
            "id": 54,
            "question_id": "16",
            "text": "BAD",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "2",
            "responded": 2
        }
    ]
},

总的来说,我想为每个答案变量添加像$respond = $answer->reports()->count();Help PLease!!

标签: laravel

解决方案


在将该数组分配给新的问题对象属性之前,我会从数据库中获取答案。

public function get() {
  // fetch parent question
  $question = Question::where('title', $title)->get();

  // fetch answers
  $answers = Answers::where('parent_id', $question->id)->get();

  // create property called "answers"
  $question->answers = $answers;

  return response()->json($question);
}

推荐阅读