UserRoleModel.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. // 设置json类型字段
  17. protected $json = ['privileges'];
  18. // 设置JSON数据返回数组
  19. protected $jsonAssoc = true;
  20. /**
  21. * 获取角色列表
  22. * @param int $merchantId 商户ID
  23. * @return \think\Collection
  24. */
  25. public static function getRoleList(int $merchantId)
  26. {
  27. return self::where('merchant_id', $merchantId)
  28. ->field('id, role_name, privileges, create_time, update_time')
  29. ->order('id', 'desc')
  30. ->select();
  31. }
  32. /**
  33. * 获取角色详情
  34. * @param int $id 角色ID
  35. * @param int $merchantId 商户ID
  36. * @return array|\think\Model|null
  37. */
  38. public static function getRoleById(int $id, int $merchantId)
  39. {
  40. return self::where('id', $id)
  41. ->where('merchant_id', $merchantId)
  42. ->find();
  43. }
  44. /**
  45. * 创建角色
  46. * @param array $data 角色数据
  47. * @return \think\Model
  48. */
  49. public static function createRole(array $data)
  50. {
  51. return self::create($data);
  52. }
  53. /**
  54. * 更新角色
  55. * @param int $id 角色ID
  56. * @param int $merchantId 商户ID
  57. * @param array $data 更新数据
  58. * @return
  59. */
  60. public static function updateRole(int $id, int $merchantId, array $data)
  61. {
  62. return self::where('id', $id)
  63. ->where('merchant_id', $merchantId)
  64. ->update($data);
  65. }
  66. /**
  67. * 删除角色
  68. * @param int $id 角色ID
  69. * @param int $merchantId 商户ID
  70. * @return bool
  71. */
  72. public static function deleteRole(int $id, int $merchantId)
  73. {
  74. return self::where('id', $id)
  75. ->where('merchant_id', $merchantId)
  76. ->delete();
  77. }
  78. /**
  79. * 检查角色是否存在
  80. * @param string $roleName 角色名称
  81. * @param int $merchantId 商户ID
  82. * @param int|null $excludeId 排除的ID
  83. * @return bool
  84. */
  85. public static function checkRoleExists(string $roleName, int $merchantId, ?int $excludeId = null): bool
  86. {
  87. $query = self::where('role_name', $roleName)
  88. ->where('merchant_id', $merchantId);
  89. if ($excludeId) {
  90. $query->where('id', '<>', $excludeId);
  91. }
  92. return $query->count() > 0;
  93. }
  94. }