簡體   English   中英

在 laravel 分頁中添加一些數據

[英]Add some data in laravel paginate

正如標題所說,這是我的控制器

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

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

並像這樣獲取 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? 

我試圖這樣做:

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

但是,它似乎會刪除列printWord 任何的想法?

您可以手動使用自定義數據創建集合並使用merge()助手:

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

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

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

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

剛剛檢查,它工作得很好。

如果您“手動”使用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;
    }
};

結果

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

自己實例化LengthAwarePaginator一些額外的工作,但它可以完成工作。

paginate 函數將返回一個Illuminate\\Pagination\\LengthAwarePaginator類型的對象,不可能只向它添加另一個字段。

我認為最適合您的解決方案是在數組中添加分頁對象和其他值,然后將此數組轉換為 json。 這樣,您的圖書數據就與您要添加的其他數據分開了。

像這樣:

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

在這種情況下,您的 json 對象將如下所示:

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

您還可以使用 eloquent 從模型中獲取數據,例如,假設每個數據都有一個汽車、書籍和寵物的列表。 您的數據模型文件應該有一個方法來聲明與這些類的“有很多”關系,如下所示:

數據模型文件

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);
}

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

汽車模型文件

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

最后,要獲得分頁的結果以及與汽車、書籍和寵物相關的所有數據,實現應該是:

控制器中的方法

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

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

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

我希望這個替代方案對您或其他開發人員有用!

終於想通了這一點。 如果您嘗試返回 json 或數組結果,只需先將分頁數據更改為數組。 然后將您需要的屬性添加到數組中。

$results = $data->paginate()->toArray();
$results['new_attribute'] = 'Attribute Value';
return response()->json($result);

合並或附加到分頁數據不起作用,因為當 json() 方法將其轉換為數組時它會丟失。 因此,通過先將其轉換為數組,您可以修改最終結果。

修改現有分頁數據發送更新響應。

    $itemsPaginated = $this->items()
         ->paginate(15);

    $itemsTransformed = $itemsPaginated
        ->getCollection()
        ->map(function($item) {
            return [
                'id' => $item->id,
            ];
    })->toArray();

    $itemsTransformedAndPaginated = new \Illuminate\Pagination\LengthAwarePaginator(
        $itemsTransformed,
        $itemsPaginated->total(),
        $itemsPaginated->perPage(),
        $itemsPaginated->currentPage(), [
            'path' => \Request::url(),
            'query' => [
                'page' => $itemsPaginated->currentPage()
            ]
        ]
    );

我相信正確的方法是創建一個資源(參見https://laravel.com/docs/8.x/eloquent-resources )並為此使用 additional() 方法。 一個常見的用例是顯示分頁結果集,同時顯示整個集合的總計。

// collect the grand total
$grandTotal = $customer->invoices()->sum('amount_excl');

// prepare the result set
$data = InvoiceResource::collection($customer->invoices()->paginate(10));

// inject additional data
$data->additional(['extra'=>['total_amount' => $grandTotal]]);
return $data;

您將獲得正確的元數據響應,以及在單獨的“額外”屬性中添加的數據。

{
 data: [{id: 15922, identifier: "12345", amount_excl: 143.27,…},…]
 extra: {total_amount: 6554.35}
 links: {first: "https://your.url.com/customers/80/invoices?page=1",…}
 meta: {current_page: 1, from: 1, last_page: 5, path: 
}
$book = Data::where('userId','1')->paginate(3); 
$book = $book->toArray();
$book['printWord'] = 'Hellow!';
return response()->json($book);

這將起作用。 您可以將分頁對象轉換為數組,然后您需要將元素添加到數組中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM