UserRoleModel.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\model;
  4. use think\Model;
  5. /**
  6. * 角色模型
  7. */
  8. class UserRoleModel extends Model
  9. {
  10. // 设置表名
  11. protected $name = 'user_role';
  12. // 设置主键
  13. protected $pk = 'id';
  14. // 开启自动时间戳
  15. protected $autoWriteTimestamp = 'int';
  16. // 定义时间戳字段名
  17. protected $createTime = 'create_time';
  18. protected $updateTime = 'update_time';
  19. // 设置json类型字段
  20. protected $json = ['privileges'];
  21. // 设置JSON数据返回数组
  22. protected $jsonAssoc = true;
  23. /**
  24. * 获取角色列表
  25. * @param int $merchantId 商户ID
  26. * @return \think\Collection
  27. */
  28. public static function getRoleList(int $merchantId)
  29. {
  30. return self::where('merchant_id', $merchantId)
  31. ->field('id, role_name, privileges, create_time, update_time')
  32. ->order('id', 'desc')
  33. ->select();
  34. }
  35. /**
  36. * 获取角色详情
  37. * @param int $id 角色ID
  38. * @param int $merchantId 商户ID
  39. * @return array|\think\Model|null
  40. */
  41. public static function getRoleById(int $id, int $merchantId)
  42. {
  43. return self::where('id', $id)
  44. ->where('merchant_id', $merchantId)
  45. ->find();
  46. }
  47. /**
  48. * 创建角色
  49. * @param array $data 角色数据
  50. * @return \think\Model
  51. */
  52. public static function createRole(array $data)
  53. {
  54. return self::create($data);
  55. }
  56. /**
  57. * 更新角色
  58. * @param int $id 角色ID
  59. * @param int $merchantId 商户ID
  60. * @param array $data 更新数据
  61. * @return
  62. */
  63. public static function updateRole(int $id, int $merchantId, array $data)
  64. {
  65. return self::where('id', $id)
  66. ->where('merchant_id', $merchantId)
  67. ->update($data);
  68. }
  69. /**
  70. * 删除角色
  71. * @param int $id 角色ID
  72. * @param int $merchantId 商户ID
  73. * @return bool
  74. */
  75. public static function deleteRole(int $id, int $merchantId)
  76. {
  77. return self::where('id', $id)
  78. ->where('merchant_id', $merchantId)
  79. ->delete();
  80. }
  81. /**
  82. * 检查角色是否存在
  83. * @param string $roleName 角色名称
  84. * @param int $merchantId 商户ID
  85. * @param int|null $excludeId 排除的ID
  86. * @return bool
  87. */
  88. public static function checkRoleExists(string $roleName, int $merchantId, ?int $excludeId = null): bool
  89. {
  90. $query = self::where('role_name', $roleName)
  91. ->where('merchant_id', $merchantId);
  92. if ($excludeId) {
  93. $query->where('id', '<>', $excludeId);
  94. }
  95. return $query->count() > 0;
  96. }
  97. }