[英]how to add custom(new) column in laravel pagination collection result
我正在創建一個API,我想在分頁查詢的結果中添加額外的列。 例如,我的數據庫中有價格和折扣。 我想發送帶有結果集的discounted_price
列。
到目前為止,這是我嘗試過的:
控制器:
$products = Products::latest()->paginate(10);
if (! empty($products)) {
$final_prod = [];
foreach ($products as $product) {
$final_prod[] = $product->asFilterJson();
}
$data['products'] = $final_prod;
$data['status'] = 200;
} else {
$data['error'] = "No product available";
}
在我的產品模型中
public function asFilterJson() {
$json = [];
$json['id'] = $this->id;
$json['title'] = $this->title;
$json['category_id'] = $this->category_id;
$json['price'] = $this->price;
$json['description'] = $this->description;
$json['quantity'] = $this->quantity;
$json['discount'] = $this->discount;
$json['type_id'] = $this->type_id;
$json['created_by_id'] = $this->created_by_id;
$json['created_at'] = $this->created_at;
$json['updated_at'] = $this->updated_at;
if($this->type_id == self::ITEM_SPECIAL) {
$json['discounted_price'] = ($this->discount * $this->price) / 100; }
return $json;
}
它工作正常,但消除了分頁。
您可以使用map方法在集合對象中添加鍵和值
$products = Products::latest()->paginate(10);
$itemSpecial = self::ITEM_SPECIAL; //pass variable in closure by using use
$products->map(function($item) use ($itemSpecial) {
if($item->type_id == $itemSpecial) {
$item->discounted_price = ($item->discount * $item->price) / 100;
}
return $item;
});
你也可以在條件中使用條件
在控制器中
public function index() {
$products = Products::latest()->paginate(10);
if (! empty($products)) {
$final_prod = [];
foreach ($products as $product) {
$final_prod[] = $this->asFilterJson($product);
}
return response()->json(['status'=>'200','message'=>'Product list ','data'=>$final_prod]);
} else {
return response()->json(['status'=>'200','message'=>'No product available','data'=>[]]);
}
}
// function for extra column add
static function asFilterJson($product){
$value['discounted_price'] = ($value['discount'] * $value['price']) / 100;
return $value;
}
您可以在模型中定義新的增變器。
public function getDiscountedPriceAttribute()
{
return ($this->discount * $this->price) / 100;
}
之后,您可以將其用作$ this-> discountedPrice
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.