屬性增強雄辯的收集功能。 該屬性提供了一種簡化的方法,可以定制特定型號類型的集合,從而促進清潔劑,更可維護的代碼。 忘記覆蓋CollectedBy
方法; newCollection()
在班級級別提供聲明的解決方案。 CollectedBy
以前,
的方法。 這種新的基於屬性的方法提供了一個卓越的類級解決方案。 newCollection()
>
use Illuminate\Database\Eloquent\Attributes\CollectedBy; #[CollectedBy(CustomCollection::class)] class YourModel extends Model { // Model implementation }考慮電子商務產品目錄:
// 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; } }
屬性簡化了集合的自定義,從而產生了更清潔,更可讀的Laravel應用程序。
以上是使用收集的Laravel自定義的詳細內容。更多資訊請關注PHP中文網其他相關文章!