Files
water_new/docs/Trait doc.md
2023-03-08 09:16:04 +08:00

2.1 KiB
Raw Permalink Blame History

Trait

1. HasClicks

缓存的浏览计数器

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

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

基础状态的显示与作用域查询

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有些时候在模块外部需要写入关联模型等时候可以使用。

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 字段


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();