model = new \app\admin\model\Message; $this->view->assign("typeList", $this->model->getTypeList()); } /** * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法 * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑 * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改 */ /** * 查看 * * @return string|Json * @throws \think\Exception * @throws DbException */ public function index() { //设置过滤方法 $this->request->filter(['strip_tags', 'trim']); if (false === $this->request->isAjax()) { return $this->view->fetch(); } //如果发送的来源是 Selectpage,则转发到 Selectpage if ($this->request->request('keyField')) { return $this->selectpage(); } [$where, $sort, $order, $offset, $limit] = $this->buildparams(); $list = $this->model ->auth($this->auth) ->where($where) ->where('type',1) ->order($sort, $order) ->paginate($limit); $result = ['total' => $list->total(), 'rows' => $list->items()]; $update = []; foreach ($list as &$item){ $readUids = explode(',',$item->read_uid??''); $item->status = 1; if(!in_array($this->auth->id,$readUids)){ $readUids[] = $this->auth->id; $update[] = [ 'id' => $item->id, 'read_uid' => implode(',',$readUids), 'update_time' => date('Y-m-d H:i:s') ]; $item->status = 0; } } if($update){ $this->batchUpdateByIdSimple('fa_message',$update); } return json($result); } /** * 通用批量更新方法(自动识别主键和字段,无循环) * * @param string $table 表名 * @param array $data 数据数组,格式如 [['id' => 1, 'field1' => 'v1'], ['id' => 2, 'field1' => 'v2']] * @param string $idField 主键字段名,默认 'id' * @return int 更新影响行数 */ protected function batchUpdateByIdSimple(string $table, array $data, string $idField = 'id'): int { if (empty($data)) return 0; $ids = array_column($data, $idField); $fields = array_keys(array_diff_key($data[0], [$idField => ''])); $sqlParts = []; foreach ($fields as $field) { $case = "CASE {$idField}"; foreach ($data as $row) { $id = intval($row[$idField]); $val = addslashes($row[$field]); $case .= " WHEN {$id} THEN '{$val}'"; } $case .= " END"; $sqlParts[] = "{$field} = {$case}"; } $sql = sprintf( "UPDATE %s SET %s WHERE %s IN (%s)", $table, implode(", ", $sqlParts), $idField, implode(',', array_map('intval', $ids)) ); return Db::execute($sql); } public function getNoreadCount() { $count = 0; //超管不提醒新消息 if(!$this->auth->isSuperAdmin()){ $count = $this->model ->where('type',1) ->auth($this->auth) //->whereRaw("FIND_IN_SET(?, read_uid) = 0 OR read_uid IS NULL OR read_uid = ''", [$this->auth->id]) ->whereRaw("FIND_IN_SET({$this->auth->id}, read_uid) = 0 OR read_uid = '' or read_uid is null") ->count(); } return [ 'count' => $count ]; } }