从集合中获取最高值

bksxznpy  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(289)

我有一系列产品,例如。

Collection {#567 ▼ 

# items: array:3 [▼

0 => Product {#571 ▼
  #searchable: array:1 [▶]
  #fillable: array:17 [▶]
  #hidden: []
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:19 [▼
    "id" => 12
    "brand_id" => null
    "sku" => "1002796"
    "name" => "In quo vero error dolorem est."
    "slug" => "in-quo-vero-error-dolorem-est"
    "description" => "<p>Dicta ipsum quis soluta pariatur iure rerum quo. Voluptatibus nulla eveniet ab esse vero. Atque et quod fuga non.</p>"
    "cover" => "products/W2INR8joy2tLuRLOXv4h5r51I7Vpcjq3hXemzvzI.png"
    "quantity" => 10
    "price" => "5.00"
    "sale_price" => "10.00"
    "status" => 1
    "length" => null
    "width" => null
    "height" => null
    "distance_unit" => null
    "weight" => "5.00"
    "mass_unit" => "lbs"
    "created_at" => "2018-08-30 17:27:30"
    "updated_at" => "2018-09-11 14:30:54"
  ]
  #original: array:21 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:1 [▶]
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
  #search_bindings: []
}
1 => Product {#568 ▶}
2 => Product {#569 ▶}
]}

所以我需要的是得到一个产品的折扣价格是最高的。在这种情况下,折扣价格是价格-销售价格。到目前为止,我尝试了从收集中循环这些项目,并尝试了一些收集方法,如过滤,减少,以获得其中的产品有最好的折扣价格,但我一直没有成功的结果。可能是我做错了什么,或者我完全失去了一部分。
感谢任何愿意帮助我的人。:)

l5tcr1uw

l5tcr1uw1#

使用 sortByDesc() :

$max = $products->sortByDesc(function($product) {
    return $product->price - $product->sale_price;
})->first();

相关问题