简体   繁体   English

如何从 Laravel 中的单个请求对相关表进行分页

[英]How to Paginate Related Table From a Single Request in Laravel

I'm new to Laravel and PHP in general and was wondering how I could paginate the tweets data in my example below:一般来说,我是 Laravel 和 PHP 的新手,想知道如何在下面的示例中对推文数据进行分页:

Route::get("/users/{user}", function (User $user) {
    return $user->only(
        "id",
        "name",
        "username",
        "avatar",
        "profile",
        "location",
        "link",
        "linkText",
        "created_at",
        "tweets"
    );
});

在此处输入图像描述

The tweets table is related to user so I could say $user->tweets()->paginate(10); tweets表与user相关,所以我可以说$user->tweets()->paginate(10); but how can I return that along with my only() method?但是我怎样才能将它与我的only()方法一起返回呢? also, is there a way for me to return multiple stuffs and can still access them on my frontend?另外,有没有办法让我返回多个东西并且仍然可以在我的前端访问它们?

You might want to look into API resources .您可能需要查看API 资源

The only() function is to be used after the query has completed, because it strips data from your model even though you have retrieved them from the database. only() function 将查询完成后使用,因为它会从您的 model 中剥离数据,即使您已经从数据库中检索了它们。 Your call to tweets() makes it a query object (without the () it would resolve to a collection object), so you are still able to chain query functions.您对tweets()的调用使其成为一个查询 object(没有()它将解析为一个集合对象),因此您仍然可以链接查询函数。

I suppose you could also call $user->tweets()->select(['id', 'user_id', 'body', ...])->paginate(10);我想你也可以调用$user->tweets()->select(['id', 'user_id', 'body', ...])->paginate(10); to only select the columns you need.只有 select 您需要的列。

If you want a more customizable pagination, you can try using limit and offset or skip and take then look into API Resource as suggested above如果你想要一个更可定制的分页,你可以尝试使用limitoffset或者skip然后take上面的建议查看API Resource

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM