【问题标题】:how to add custom(new) column in laravel pagination collection result如何在 laravel 分页收集结果中添加自定义(新)列
【发布时间】:2018-12-31 10:43:27
【问题描述】:

我正在创建一个 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;
}

它工作正常,但它消除了分页。

【问题讨论】:

  • 新建一个集合,并使用 $products->merge(...);
  • 请添加您从控制器返回的代码

标签: php laravel laravel-collection laravel-pagination


【解决方案1】:

您可以使用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;
});

你也可以使用条件

【讨论】:

    【解决方案2】:

    在控制器中

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

    【讨论】:

    • 它删除了分页
    【解决方案3】:

    您可以在模型中定义新的 mutator。

    public function getDiscountedPriceAttribute()
    {
         return ($this->discount * $this->price) / 100;
    }
    

    之后,你可以把它当作$this->discountedPrice

    【讨论】:

    • 让我检查一下
    • 是的。 Jignesh 的回答很有帮助,解决了我的问题
    猜你喜欢
    • 2020-03-22
    • 2018-05-21
    • 2020-10-18
    • 1970-01-01
    • 2015-09-21
    • 2014-05-08
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    相关资源
    最近更新 更多