属性增强雄辩的收集功能。 该属性提供了一种简化的方法,可以定制特定型号类型的集合,从而促进清洁剂,更可维护的代码。 忘记覆盖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中文网其他相关文章!