laravel - 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!!
解决方案
在将该数组分配给新的问题对象属性之前,我会从数据库中获取答案。
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);
}
推荐阅读
- spring - 避免在控制台 Spring Boot 上“绑定参数”日志
- jackson - 如何在 Jackson 中使用 XmlMapper 处理 GZipInputStream?
- c++ - 预处理:定义“import”的简写是否合法?
- python - 如何在链接中添加数字(循环)
- python - Dask Future 的状态为“已取消”,但未被取消
- json - 有没有办法在 RML 中自动生成 ID/UUID?
- javascript - React app 提示:Typeerror _ service worker webpack_imported_module _4 is not a function
- typescript - 用于多种身份验证选项的服务器端编程设计(打字稿护照)
- postgresql - 使用 Confluent JDBC 连接器忽略更新缺失的字段
- python - 如何获得两列之间的相关性?