我试图将Json响应作为对象数组返回。但是相反,我得到了作为对象的响应。我有condition_question表,用于保存question_id和condition_id。我想检索所有包含特定条件ID的问题。并按answers_number对其进行排序。我是Laravel的新手,这是我的代码:
$conditionsIdArray = array($chosenConditionsIds);
$results = Question::whereIn('question_id', function ($query) use ($conditionsIdArray) {
$query->select('question_id')
->from('condition_question')
->whereIn('condition_id', $conditionsIdArray);
})->get()->sortByDesc('answers_number')->take(5);
return response()->json([
'questions' => $results
], 200);
我得到回应:
{
"questions": {
"0": {
"question_id": 842,
"question_title": "Qui tempora...",
"question_body": "Repellendus non sint...",
"image": "https://lorempixel.com/640/480/?18901",
"question_view_count": 17,
"votes_number": 9,
"answers_number": 9,
"id_user": 9930,
"created_at": "2019-09-07 09:59:05",
"updated_at": "2019-09-08 18:23:41"
},
"28": {
"question_id": 20346,
"question_title": "Quaerat facere...",
"question_body": "Repudiandae culpa ...",
"image": "https://lorempixel.com/640/480/?91963",
"question_view_count": 2,
"votes_number": 2,
"answers_number": 9,
"id_user": 3546,
"created_at": "2019-09-07 10:07:38",
"updated_at": "2019-09-07 10:07:38"
},etc
}
如您所见,我得到了带有物体的物体。我不想要键/值,只是简单的对象数组类型为Question。 我现在挣扎了两天,尝试了一些不同的东西,例如toArray(),但不知道如何解决。任何帮助将是最欢迎的。
答案 0 :(得分:3)
如果更改索引数组中的键,由于排序并取5,索引将关闭,它会认为它具有关联数组。在Laravel
集合上有一个values()
method,您可以在其中调用它来重新索引集合。
return response()->json([
'questions' => $results->values()
], 200);