在 laravel paginate 中添加一些数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41034351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:54:03  来源:igfitidea点击:

Add some data in laravel paginate

phplaravellaravel-5paginate

提问by Fan

As the tittle said, Here is my Controller

正如标题所说,这是我的控制器

$book = Data::where('userId','1')->paginate(3);

return response()->json($book);

And get the json data like this:

并像这样获取json数据:

data:[{id: 1, userId: 1, vendorId: 1, name: "Alfreda Berge PhD", phone: "1-850-813-5950 x96169",…},…]
from:1
last_page:2
next_page_url: "http:/localhost/XX/public/user/book/list/1?page=2"
perpage:4
prev_page_url:null
to:4
total:5
// if I want to add a new column and value here ,what should I do? 

I tried to do this :

我试图这样做:

$book = Data::where('userId','1')->paginate(3);
$book->printWord = 'Hellow!';
return response()->json($book);

But, It seem will remove the column printWord. Any idea?

但是,它似乎会删除列printWord。任何的想法?

回答by Alexey Mezenin

You can create collection with custom data manually and use merge()helper:

您可以手动使用自定义数据创建集合并使用merge()帮助程序:

$book = Data::where('userId','1')->paginate(3);

$custom = collect(['my_data' => 'My custom data here']);

$data = $custom->merge($book);

return response()->json($data);

Just checked, it works just fine.

刚刚检查,它工作得很好。

回答by BrunoRB

If you use the Illuminate\Pagination\LengthAwarePaginatorclass "manually", there's the option of extending it and overriding the toArraymethod:

如果您“手动”使用Illuminate\Pagination\LengthAwarePaginator类,则可以选择扩展它并覆盖该toArray方法:

return new class(
    $collection,
    $count,
    $limit,
    $page,
    // https://github.com/laravel/framework/blob/6.x/src/Illuminate/Pagination/LengthAwarePaginator.php#L40
    // values here will become properties of the object
    [
        'seed' => $seed
    ]
) extends LengthAwarePaginator {
    public function toArray()
    {
        $data = parent::toArray();
        // place whatever you want to send here
        $data['seed'] = $this->seed;
        return $data;
    }
};

Result

结果

current_page    1
data    []
first_page_url  "/finder?max_miles=100&zip_code=10001&seed=0.2&page=1"
from    null
last_page   1
last_page_url   "/finder?max_miles=100&zip_code=10001&seed=0.2&page=1"
next_page_url   null
path    "/finder"
per_page    20
prev_page_url   null
to  null
total   0
seed    0.2 // <-- our custom prop

There's some extra work involved with instantiating LengthAwarePaginatoryourself, but it gets the job done.

实例化LengthAwarePaginator自己需要一些额外的工作,但它可以完成工作。

回答by Jerodev

The paginate function will return an object of the type Illuminate\Pagination\LengthAwarePaginator, it is not possible to just add another field to this.

paginate 函数将返回一个类型为 的对象,Illuminate\Pagination\LengthAwarePaginator不可能只向 this 添加另一个字段。

I think the best solution for you would be to add the pagination object and the other values in an array and convert this array to json. This way your books data is seperated from the other data you want to add.

我认为最适合您的解决方案是在数组中添加分页对象和其他值,然后将此数组转换为 json。这样,您的图书数据就与您要添加的其他数据分开了。

Like so:

像这样:

return response()->json([
    'books' => $books,
    'foo' => 'bar'
]);

In this case your json object will look like this:

在这种情况下,您的 json 对象将如下所示:

{
    books: {
        // Pagination object with books
    }
    foo: 'bar'
}

回答by Yor Jaggy

You can also obtain data from your model using eloquent, for example, let say that each Data has a list of cars, books, and pets. Your Data model file should have a method that declares the "has many" relations with those classes, like below:

您还可以使用 eloquent 从模型中获取数据,例如,假设每个数据都有一个汽车、书籍和宠物的列表。您的数据模型文件应该有一个方法来声明与这些类的“有很多”关系,如下所示:

Data model file

数据模型文件

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Data extends Model{

protected $table = 'data';

protected $fillable = [
    'id', 'user_id', 'vendorId', 'name', 'phone'
];

public function cars(){
    return $this->hasMany(Car::class);
}

public function books(){
    return $this->hasMany(Book::class);
}

public function pets(){
    return $this->hasMany(Pet::class);
}

Also, you must have the "belongsTo" method in every Car, Book, and Pet model.

此外,您必须在每个 Car、Book 和 Pet 模型中都有“belongsTo”方法。

Car model file

汽车模型文件

...
public function data(){
    return $this->belongsTo(Data::class);
}
...

Finally, to obtain your results paginated and with all the data related to cars, books, and pets, the implementation should be:

最后,要获得分页的结果以及与汽车、书籍和宠物相关的所有数据,实现应该是:

Method in your Controller

控制器中的方法

$data_elements = Data::where('userId','1')->paginate(3);

foreach($data_elements as $d){
    $d->cars;
    $d->books;
    $d->pets;
}

return response()->json($data_elements);

I hope this alternative be useful for you or for some other developer!

我希望这个替代方案对您或其他开发人员有用!