[toc] # 问题 查询时指定`field`无效,可能是模型关联查询存在什么bug。 以下是我buildQuery是我封装的。返回`\think\Query` ```php $field = ['tm.tag_id', 'count(*) as `count`']; $result = $query->join($join)->group('tm.tag_id')->limit(15)->field($field)->select(); ``` sql ```sql SELECT `mz_file`.`id`,`mz_file`.`title`,`mz_file`.`topicid`,`mz_file`.`filename`,`mz_file`.`extension`,`mz_file`.`url`,`mz_file`.`hdurl`,`mz_file`.`hdsize`,`mz_file`.`sdurl`,`mz_file`.`sdsize`,`mz_file`.`thumbnail`,`mz_file`.`public`,`mz_file`.`type`,`mz_file`.`definition`,`mz_file`.`width`,`mz_file`.`height`,`mz_file`.`mimetype`,`mz_file`.`size`,`mz_file`.`desc`,`mz_file`.`uploaduserid`,`mz_file`.`tag`,`mz_file`.`sensitive`,`mz_file`.`sensitivestatus`,`mz_file`.`auditstatus`,`mz_file`.`auditreason`,`mz_file`.`shuttertime`,`mz_file`.`createtime`,`mz_file`.`updatetime`,`mz_file`.`deletetime`,topic.id AS topic__id,topic.category_id AS topic__category_id,topic.title AS topic__title,topic.thumbnail AS topic__thumbnail,topic.public AS topic__public,topic.size AS topic__size,topic.type AS topic__type,topic.master_file_id AS topic__master_file_id,topic.createuserid AS topic__createuserid,topic.desc AS topic__desc,topic.tag AS topic__tag,topic.status AS topic__status,topic.createtime AS topic__createtime,topic.updatetime AS topic__updatetime,topic.deletetime AS topic__deletetime,`tm`.`tag_id`,count(*) as `count` FROM `fa_pan_file` `mz_file` INNER JOIN `fa_pan_topic` `topic` ON `mz_file`.`topicid`=`topic`.`id` INNER JOIN `fa_pan_tagmap` `tm` ON `tm`.`type`='file' AND tm.file_id = mz_file.id WHERE ( `mz_file`.`public` = '1' AND `mz_file`.`auditstatus` = 2 ) AND `mz_file`.`deletetime` IS NULL GROUP BY `tm`.`tag_id` ORDER BY `mz_file`.`shuttertime` DESC LIMIT 15 ``` 老血没吐出来, 不听field()的。应该是个bug # 解决办法 取出sql,使用以下函数替换field部分,再用`Db::query`执行 ```php if (function_exists('sql_replace_field') == false) { /** * sql替换field * * @param string $sql * @param string $field * @return string */ function sql_replace_field($sql, $field) { $arr = explode(' ', $sql); $arr = array_filter($arr); // 可能存在多个空格,分割空字符串会导致while终止 $result = ''; while ($item = array_shift($arr)) { if (strtoupper($item) === 'SELECT') { $item = $item . ' ' . $field . ' FROM'; while($tmp = array_shift($arr)) { if (strtoupper($tmp) === 'FROM') { break; } } } $result = $result . $item . ' '; } return trim($result); } } ```