--------------------------------------
文件代码 https://github.com/top-think/think-orm/blob/0b01a19654c3b0376043960a30e74c9ddb55d574/src/db/Query.php#L54-L62
/**
* 指定Field排序 orderField('id',[1,2,3],'desc')
* @access public
* @param string $field 排序字段
* @param array $values 排序值
* @param string $order 排序 desc/asc
* @return $this
*/
public function orderField(string $field, array $values, string $order = '')
文件代码 https://github.com/top-think/think-orm/blob/0b01a19654c3b0376043960a30e74c9ddb55d574/src/db/Builder.php#L951-L977 /**
* orderField分析
* @access protected
* @param Query $query 查询对象
* @param string $key
* @param array $val
* @return string
*/
protected function parseOrderField(Query $query, string $key, array $val): string
{
if (isset($val['sort'])) {
$sort = $val['sort'];
unset($val['sort']);
} else {
$sort = '';
}
$sort = strtoupper($sort);
$sort = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : '';
$bind = $query->getFieldsBindType();
foreach ($val as $item) {
$val[] = $this->parseDataBind($query, $key, $item, $bind);
}
return 'field(' . $this->parseKey($query, $key, true) . ',' . implode(',', $val) . ')' . $sort;
}
orderField 的底层解析 parseOrderField 代码中: foreach ($val as $item) {
$val[] = $this->parseDataBind($query, $key, $item, $bind);
}
return 'field(' . $this->parseKey($query, $key, true) . ',' . implode(',', $val) . ')' . $sort;
并没有把输入参数替换成值绑定(用的 $val[] 追加),导致后面的 implode(',', $val) 直接把原始值带入sql。解决方法:把 foreach 改成:
foreach ($val as $k => $item) {
$val[$k] = $this->parseDataBind($query, $key, $item, $bind);
}
最佳答案
