# Trait ## 1. HasClicks > 缓存的浏览计数器 ```php use App\Traits\HasClicks; class Test extends Model { use HasClicks; protected string $clicks_filed = 'clicks'; } $test = Test::first(); // 增加点击数量 $test->incrementClicks(1); // 获取点击量 $test->clicks; ``` ## 2. HasCovers > 封面图与轮播图的展示扩展,完整url ```php use App\Traits\HasCovers; class Test extends Model { use HasCovers; protected string $cover_field = 'cover'; protected string $pictures_field = 'pictures'; } $test = Test::first(); $test->cover_url; $test->pictures_url; ``` ## 3. HasStatus > 基础状态的显示与作用域查询 ```php use App\Traits\HasStatus; class Test extends Model { use HasStatus; protected string $status_field = 'status'; protected array $status_map = [ 1 => '正常', 0 => '禁用' ]; } // 状态为 1 的 $test = Test::shown()->first(); // 状态为 0 的 $test = Test::hidden()->first(); // 查询特定状态 $test = Test::ofStatus(3)->first(); // 状态的文本显示 $test->status_text; ``` ## 4. Macroable > 这个主要用于,对模型的一些外部扩展使用、 > > 因为模型无法动态的注入trait,有些时候在模块外部,需要写入关联模型等时候,可以使用。 ```php use App\Tratis\Macroable; class Test extends Model { use Macroable; } // 对模型注入一个 address 的一对多关联 Test::macro('address', function () { return $this->hasMany(Address::class); }); ``` ## 5. OrderByIdDesc > 直接引入模型后,查询到的数据会默认以ID 倒序排列, > > 暂时没有找到怎么获取主键的方法,待升级 ## 6. OrderByOrderAsc > 已特定的 order 字段,按照升序排序 ## 7. WithPosition > 位运算来解决的多点定位,模型中需要有 position 字段 ```php use App\Traits\WithPosition; class Test extends Model { use WithPosition; protected array $position_map = [ 1 => 'A', 2 => 'B', 4 => 'C', 8 => 'D', ]; } $test = Test::ofPosition(3)->first(); ```