Rumah >pembangunan bahagian belakang >tutorial php >Penyesuaian Koleksi di Laravel Menggunakan Dikumpulkan
CollectedBy
menyediakan penyelesaian deklaratif di peringkat kelas. newCollection()
CollectedBy
Sebelum ini, koleksi model jahitan yang melibatkan kaedah . Kaedah berasaskan atribut baru ini menawarkan penyelesaian peringkat kelas yang unggul.
newCollection()
use Illuminate\Database\Eloquent\Attributes\CollectedBy; #[CollectedBy(CustomCollection::class)] class YourModel extends Model { // Model implementation }
atribut
// Product Collection <?php namespace App\Collections; use Illuminate\Database\Eloquent\Collection; class ProductCollection extends Collection { public function inStock() { return $this->filter(fn($product) => $product->stock_count > 0); } public function onSale() { return $this->filter(fn($product) => $product->discount_percentage > 0); } public function byPriceRange($min, $max) { return $this->filter(function($product) use ($min, $max) { $price = $product->getEffectivePrice(); return $price >= $min && $price <= $max; }); } public function topRated() { return $this->filter(fn($product) => $product->average_rating >= 4) ->sortByDesc('average_rating'); } } //Product model namespace App\Models; use App\Collections\ProductCollection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Attributes\CollectedBy; #[CollectedBy(ProductCollection::class)] class Product extends Model { public function getEffectivePrice() { return $this->discount_percentage > 0 ? $this->price * (1 - $this->discount_percentage / 100) : $this->price; } }memudahkan penyesuaian koleksi, menghasilkan aplikasi Laravel yang lebih bersih, lebih mudah dibaca.
Atas ialah kandungan terperinci Penyesuaian Koleksi di Laravel Menggunakan Dikumpulkan. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!