【发布时间】:2020-05-05 14:16:16
【问题描述】:
让我们考虑一个简单的例子:一个标签有许多问题(即一对多的关系)。所以,我想要的是获得一个标签记录以及其中的消息记录的分页列表。
为此,我所做的是:
function getTagWithQuestions(Request $request, $tagId)
{
// get tag
$tag = Tag::find($tagId);
// check if it exists or not
if (!isset($tag->id)) {
return response(['message' => 'Tag not found'], 404);
}
// get paginated list of questions
$questions = Question::where(['tag_id' => $tag->id])->paginate();
// assign questions to tag
$tag->questions = QuestionResource::collection($questions);
// return the contents
return new TagResource($tag);
}
我需要的结果应该是这种格式:
{
"id": 1,
"name": "javascript",
"questions": {
"current_page": 1,
"data": [...(list of questions)],
"first_page_url": "http://127.0.0.1:8000/uv1/tags/8?page=1",
"from": 1,
"last_page": 1,
"last_page_url": "http://127.0.0.1:8000/uv1/tags/8?page=1",
"next_page_url": null,
"path": "http://127.0.0.1:8000/uv1/tags/8",
"per_page": "15",
"prev_page_url": null,
"to": 5,
"total": 5
}
}
但不知何故,我得到的结果是一个未分页的联系人数组列表。
{
"id": 1,
"name": "javascript",
"questions": [...(list of questions)]
}
有什么方法可以获得相同的输出(因为我需要分页元数据来附加分页)?
【问题讨论】:
标签: laravel eloquent pagination