(LARAVEL)从相关表(1到多)中获取带有分页记录列表的记录 让我们考虑一个简单的例子:标签有大量的问题(即1到多个关系)。所以,我想要的是得到一个标记记录以及其中的消息记录分页列表
为此,我所做的是:(LARAVEL)从相关表(1到多)中获取带有分页记录列表的记录 让我们考虑一个简单的例子:标签有大量的问题(即1到多个关系)。所以,我想要的是得到一个标记记录以及其中的消息记录分页列表,laravel,eloquent,pagination,Laravel,Eloquent,Pagination,为此,我所做的是: 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); }
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)]
}
是否有任何方法可以获得相同的输出(因为我需要分页元来附加分页)?将
$questions
转换为数组,结构将是您想要的
$questions=Question::where(['tag\u id'=>$tag->id])->paginate();
//将问题分配给标记
$tag->questions=$questions->toAarray();
//归还内容
返回新的TagResource($tag);
请记住不要将与('questions')一起使用,否则您需要分配给另一个键,如下所示:
$tag->questions\u list=$questions->toAarray();
哇,你真是个救命恩人