【问题标题】:(LARAVEL) Get a record with paginated list of records from a relating table (1 to many)(LARAVEL)从相关表(1到许多)中获取具有分页记录列表的记录
【发布时间】: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


    【解决方案1】:

    $questions转换为数组,结构就是你想要的,

    $questions = Question::where(['tag_id' => $tag->id])->paginate();
    // assign questions to tag
    $tag->questions = $questions->toAarray();
    
    // return the contents
    return new TagResource($tag);
    

    记住不要使用with('questions'),否则你需要分配给另一个键,像这样:

    $tag->questions_list = $questions->toAarray();
    

    【讨论】:

    • 哇,你救命了?,非常感谢
    猜你喜欢
    • 1970-01-01
    • 2017-04-22
    • 2022-01-12
    • 1970-01-01
    • 2021-08-31
    • 2019-02-24
    • 2015-06-22
    • 2017-07-25
    • 1970-01-01
    相关资源
    最近更新 更多