resloveData($data); $validate = $this->validate($data); if ($validate !== true) { $this->setError($validate); return false; } $model = $this->modelName::create($data); if (isset($data['jobs']) && is_string($data['jobs'])) { $this->resloveJob($model, explode(',', $data['jobs'])); } return true; } public function update($primaryKey, $data): bool { $model = $this->query()->whereKey($primaryKey)->firstOrFail(); $data = $this->resloveData($data, $model); $validate = $this->validate($data, $model); if ($validate !== true) { $this->setError($validate); return false; } if (isset($data['jobs']) && is_string($data['jobs'])) { $this->resloveJob($model, explode(',', $data['jobs'])); } return $model->update($data); } public function getEditData($id): Model|\Illuminate\Database\Eloquent\Collection|Builder|array|null { $model = $this->getModel(); $hidden = collect([$model->getCreatedAtColumn(), $model->getUpdatedAtColumn()]) ->filter(fn ($item) => $item !== null) ->toArray(); return $this->query()->with(['adminUser', 'jobs'])->find($id)->makeHidden($hidden); } public function resloveData($data, $model = null) { $adminUserService = AdminUserService::make(); if (!$model) { // 添加管理员信息 if (! $adminUserService->store(Arr::only($data, ['username', 'password', 'confirm_password']))) { $this->setError($adminUserService->getError()); return false; } $adminUser = AdminUser::where('username', $data['username'])->first(); $data['admin_user_id'] = $adminUser->id; } return $data; } /** * 处理职位关联 * * @param Employee $model * @param array $jobs(字典表 key 组成的数组) */ public function resloveJob($model, $jobs) { $model->jobs()->sync($jobs); } public function preDelete(array $ids) { // 店员关联 if (DB::table('store_employees')->whereIn('employee_id', $ids)->exists()) { return '员工已关联门店, 请先从门店中删除'; } // 删除管理员 $adminUserIds = Employee::whereIn('id', $ids)->pluck('admin_user_id')->implode(','); $adminUserService = AdminUserService::make(); $adminUserService->delete($adminUserIds); // 删除职位关联 DB::table('employee_jobs')->whereIn('employee_id', $ids)->delete(); return true; } public function validate($data, $model = null) { $createRules = [ 'name' => ['required'], 'phone' => ['required'], ]; $updateRules = []; $validator = Validator::make($data, $model ? $updateRules : $createRules, [ 'name.required' => __('employee.name').'必填', 'phone.required' => __('employee.phone').'必填', ]); if ($validator->fails()) { return $validator->errors()->first(); } return true; } }