我正在创建一个 API,我想在分页查询的结果中添加额外的列。例如,我的数据库中有价格和折扣。我想发送包含结果集的 discounted_price
列。
这是我迄今为止尝试过的:
Controller :
$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;
});
you can used condition also in clourse
关于php - 如何在 Laravel 分页集合结果中添加自定义(新)列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53986500/