UserMenuGroup.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace app\common\model;
  3. use think\Db;
  4. class UserMenuGroup extends Base
  5. {
  6. public function updates($userId){
  7. $data = request()->post();
  8. $data['user_id'] = $userId;
  9. $result = validate('UserMenuGroup')->check($data,[],'');
  10. if(true !== $result){
  11. $this->error = validate('UserMenuGroup')->getError();
  12. return false;
  13. }
  14. $id = $data['id'];
  15. unset($data['id']);
  16. Db::startTrans();
  17. try{
  18. if($id > 0){
  19. $data['update_time'] = date('Y-m-d H:i:s');
  20. $ret = $this->allowField(true)->save($data,['id'=>$id]);
  21. }else{
  22. $data['create_time'] = date('Y-m-d H:i:s');
  23. $ret = $this->allowField(true)->save($data);
  24. $id = $this->id;
  25. }
  26. if(!$ret){
  27. exception('操作失败');
  28. }
  29. $menus = $data['menus']?explode(',',$data['menus']):[];
  30. if($menus){
  31. $map[] = ['user_id','=',$data['user_id']];
  32. $map[] = ['id','<>',$id];
  33. $lists = Db::name('user_menu_group')->where($map)->select();
  34. $lists = $lists?$lists:[];
  35. foreach ($lists as $k=>$v){
  36. $omenus = $v['menus']?explode(',',$v['menus']):[];
  37. if(empty($omenus)){
  38. continue;
  39. }
  40. $nmenus = [];
  41. foreach ($omenus as $kk=>$vv){
  42. if(!in_array($vv,$menus)){
  43. $nmenus[] = $vv;
  44. }
  45. }
  46. if(count($nmenus) != count($nmenus)){
  47. $mes = $nmenus?implode(',',$nmenus):'';
  48. $res = Db::name('user_menu_group')->where('id',$v['id'])->setField('menus',$mes);
  49. if(!$res){
  50. exception('操作失败');
  51. }
  52. }
  53. }
  54. }
  55. Db::commit();
  56. }catch (\Exception $e){
  57. Db::rollback();
  58. $this->error = '操作失败';
  59. return false;
  60. }
  61. return true;
  62. }
  63. }