我有一系列产品
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 ▶}
]}
所以我需要的是获得折扣价最高的产品。在这种情况下,折价为价格-sale_price。到目前为止,我尝试从集合中循环这些项目,并尝试了诸如filter,reduce之类的一些集合方法,以获得哪种产品的折扣价最高,但我一直未能成功。可能是我做错了什么,或者我完全缺少了一部分。
感谢任何愿意帮助我的人。 :)
答案 0 :(得分:3)
使用sortByDesc()
:
$max = $products->sortByDesc(function($product) {
return $product->price - $product->sale_price;
})->first();