BaseMysql.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace App\Models\Mysql;
  3. use Hashids\Hashids;
  4. use Illuminate\Database\Eloquent\SoftDeletes;
  5. use Illuminate\Foundation\Bus\DispatchesJobs;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Illuminate\Support\Facades\DB;
  8. class BaseMysql extends Model
  9. {
  10. // 是否使用分配任务,是否支持软删
  11. // use DispatchesJobs, SoftDeletes;
  12. /**
  13. * 配置中的连接名.
  14. * @var string
  15. */
  16. public $connection = 'mysql';
  17. /**
  18. * 自定义主键名
  19. * @var string
  20. */
  21. protected $primaryKey = 'id';
  22. /**
  23. * 自动维护时间戳created_at和updated_at
  24. *
  25. * @var bool
  26. */
  27. public $timestamps = true;
  28. /**
  29. * 自增主键
  30. * @var bool
  31. */
  32. public $incrementing = true;
  33. /**
  34. * 定义分页尺码
  35. *
  36. * @var int
  37. */
  38. protected $perPage = 20;
  39. /**
  40. * 保护字段.
  41. * @var string[]
  42. */
  43. protected $guarded = ['id'];
  44. /**
  45. * 获取表名
  46. * @return mixed
  47. */
  48. public function getTable()
  49. {
  50. return $this->table;
  51. }
  52. /**
  53. * 获得数据库服务器版本
  54. * @return string
  55. */
  56. public function getDbServerVersion()
  57. {
  58. return DB::getPdo()->getAttribute(\PDO::ATTR_SERVER_VERSION);
  59. }
  60. /**
  61. * 获取表前缀
  62. * @return string
  63. */
  64. public function getTablePrefix()
  65. {
  66. return DB::getTablePrefix();
  67. }
  68. /**
  69. * 生成一个ID
  70. *
  71. * @param string $idName 查询唯一ID字段名.
  72. * @param integer $length 长度.
  73. * @param string $pkValue 主键值.
  74. *
  75. * @return string
  76. */
  77. public static function generateId(string $idName, $length = 8, $pkValue = '')
  78. {
  79. if ($length <= 3) {
  80. $length = 8;
  81. }
  82. if (!empty($pkValue)) {
  83. $uuid = hashEncodeId($pkValue);
  84. } else {
  85. $uuid = rand_letter(1) . (random($length - 1));
  86. if (self::query()->where($idName, $uuid)->exists()) {
  87. // 存在则继续生成,直到新的出现.
  88. return self::generateId($idName, $length, $pkValue);
  89. }
  90. }
  91. return $uuid;
  92. }
  93. }