我在 CakePHP 中有以下代码。
<th> <?php echo $this->Paginator->sort('standard_id', 'Standard'); ?></th>
<th> <?php echo $this->Paginator->sort('id'); ?> </th>
<th> <?php echo $this->Paginator->sort('title'); ?> </th>
我的 standard_id
数据是这样的:
- 第三名
- 第四名
- 第十名
- 11日
- ...等等
我的问题是 standard_id
没有正确排序,它正在将其视为字符串。我想应用数字排序。
有什么想法吗?
最佳答案
将以下内容添加到您的模型中:
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields['standard_id_numeric'] = sprintf('CAST(%s.standard_id as UNSIGNED)', $this->alias);
}
现在您应该可以按 standard_id_numeric
排序了。
或者,您可以将虚拟字段声明为:
public $virtualFields = array(
'standard_id_numeric' => 'CAST(Standard.standard_id as UNSIGNED)'
);
但是,如果您使用别名实例化您的模型,这将引发错误。
见
- Cookbook 2.x:虚拟字段:Pagination and virtual fields .
关于mysql - CakePHP 分页器中的数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35695737/