UserRole.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\store\model\store;
  13. use app\common\model\store\UserRole as UserRoleModel;
  14. /**
  15. * 商家用户角色模型
  16. * Class UserRole
  17. * @package app\store\model\store
  18. */
  19. class UserRole extends UserRoleModel
  20. {
  21. /**
  22. * 新增关系记录
  23. * @param int $storeUserId
  24. * @param array $roleIds
  25. * @return array|false
  26. */
  27. public static function increased(int $storeUserId, array $roleIds)
  28. {
  29. $data = [];
  30. foreach ($roleIds as $roleId) {
  31. $data[] = [
  32. 'store_user_id' => $storeUserId,
  33. 'role_id' => $roleId,
  34. 'store_id' => self::$storeId,
  35. ];
  36. }
  37. return (new static)->addAll($data);
  38. }
  39. /**
  40. * 更新关系记录
  41. * @param int $storeUserId
  42. * @param array $newRoles 新的角色集
  43. * @return array|false
  44. */
  45. public static function updates(int $storeUserId, array $newRoles)
  46. {
  47. // 已分配的角色集
  48. $assignRoleIds = self::getRoleIdsByUserId($storeUserId);
  49. // 找出删除的角色
  50. $deleteRoleIds = array_diff($assignRoleIds, $newRoles);
  51. if (!empty($deleteRoleIds)) {
  52. self::deleteAll([
  53. ['store_user_id', '=', $storeUserId],
  54. ['role_id', 'in', $deleteRoleIds]
  55. ]);
  56. }
  57. // 找出添加的角色
  58. $newRoleIds = array_diff($newRoles, $assignRoleIds);
  59. $data = [];
  60. foreach ($newRoleIds as $roleId) {
  61. $data[] = [
  62. 'store_user_id' => $storeUserId,
  63. 'role_id' => $roleId,
  64. 'store_id' => self::$storeId,
  65. ];
  66. }
  67. return (new static)->addAll($data);
  68. }
  69. /**
  70. * 获取指定管理员的所有角色id
  71. * @param int $storeUserId
  72. * @return array
  73. */
  74. public static function getRoleIdsByUserId(int $storeUserId): array
  75. {
  76. return (new static)->where('store_user_id', '=', $storeUserId)->column('role_id');
  77. }
  78. /**
  79. * 根据角色ID判断是否存在用户
  80. * @param int $roleId
  81. * @return bool
  82. */
  83. public static function isExistsUserByRoleId(int $roleId): bool
  84. {
  85. return !!(new static)->where('role_id', '=', $roleId)->count();
  86. }
  87. }