| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- <?php
- namespace App\Models\Mysql;
- use Hashids\Hashids;
- use Illuminate\Database\Eloquent\SoftDeletes;
- use Illuminate\Foundation\Bus\DispatchesJobs;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Support\Facades\DB;
- class BaseMysql extends Model
- {
- // 是否使用分配任务,是否支持软删
- // use DispatchesJobs, SoftDeletes;
- /**
- * 配置中的连接名.
- * @var string
- */
- public $connection = 'mysql';
- /**
- * 自定义主键名
- * @var string
- */
- protected $primaryKey = 'id';
- /**
- * 自动维护时间戳created_at和updated_at
- *
- * @var bool
- */
- public $timestamps = true;
- /**
- * 自增主键
- * @var bool
- */
- public $incrementing = true;
- /**
- * 定义分页尺码
- *
- * @var int
- */
- protected $perPage = 20;
- /**
- * 保护字段.
- * @var string[]
- */
- protected $guarded = ['id'];
- /**
- * 获取表名
- * @return mixed
- */
- public function getTable()
- {
- return $this->table;
- }
- /**
- * 获得数据库服务器版本
- * @return string
- */
- public function getDbServerVersion()
- {
- return DB::getPdo()->getAttribute(\PDO::ATTR_SERVER_VERSION);
- }
- /**
- * 获取表前缀
- * @return string
- */
- public function getTablePrefix()
- {
- return DB::getTablePrefix();
- }
- /**
- * 生成一个ID
- *
- * @param string $idName 查询唯一ID字段名.
- * @param integer $length 长度.
- * @param string $pkValue 主键值.
- *
- * @return string
- */
- public static function generateId(string $idName, $length = 8, $pkValue = '')
- {
- if ($length <= 3) {
- $length = 8;
- }
- if (!empty($pkValue)) {
- $uuid = hashEncodeId($pkValue);
- } else {
- $uuid = rand_letter(1) . (random($length - 1));
- if (self::query()->where($idName, $uuid)->exists()) {
- // 存在则继续生成,直到新的出现.
- return self::generateId($idName, $length, $pkValue);
- }
- }
- return $uuid;
- }
- }
|