UserRole.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 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. * @throws \Exception
  45. */
  46. public static function updates(int $storeUserId, array $newRoles)
  47. {
  48. // 已分配的角色集
  49. $assignRoleIds = self::getRoleIdsByUserId($storeUserId);
  50. // 找出删除的角色
  51. $deleteRoleIds = array_diff($assignRoleIds, $newRoles);
  52. if (!empty($deleteRoleIds)) {
  53. self::deleteAll([
  54. ['store_user_id', '=', $storeUserId],
  55. ['role_id', 'in', $deleteRoleIds]
  56. ]);
  57. }
  58. // 找出添加的角色
  59. $newRoleIds = array_diff($newRoles, $assignRoleIds);
  60. $data = [];
  61. foreach ($newRoleIds as $roleId) {
  62. $data[] = [
  63. 'store_user_id' => $storeUserId,
  64. 'role_id' => $roleId,
  65. 'store_id' => self::$storeId,
  66. ];
  67. }
  68. return (new static)->addAll($data);
  69. }
  70. /**
  71. * 获取指定管理员的所有角色id
  72. * @param int $storeUserId
  73. * @return array
  74. */
  75. public static function getRoleIdsByUserId(int $storeUserId)
  76. {
  77. return (new static)->where('store_user_id', '=', $storeUserId)->column('role_id');
  78. }
  79. /**
  80. * 根据角色ID判断是否存在用户
  81. * @param int $roleId
  82. * @return bool
  83. */
  84. public static function isExistsUserByRoleId(int $roleId)
  85. {
  86. return !!(new static)->where('role_id', '=', $roleId)->count();
  87. }
  88. }