我有一个包含以下项目的数据库表:
| id | name | created | modified |
----------------------------------------------------------
| 10 | test1 | 2014-11-27 14:05:39 | 2014-11-27 14:05:39 |
| 11 | test1 | 2014-11-28 14:05:39 | 2014-11-28 14:05:39 |
| 12 | test2 | 2014-11-28 14:05:39 | 2014-11-28 14:05:39 |
我想按名称对项目进行分组,仅显示分组值的最后一个ID。但无论我尝试什么,都会显示第一个ID。在这个例子中,我想要ID 11和12作为输出,但是显示了项目10和12。也许这是分页的问题?
这是我正在运行的查询:
$this->paginate = array(
'limit' => 20,
'order' => array('created' => 'DESC'),
'group' => array('name')
);
但即使使用ASC,输出也保持不变......
答案 0 :(得分:0)
试试这个:
$this->paginate = array(
'limit' => 20,
'order' => array('model_name.created' => 'DESC'),
'group' => array('model_name.name')
);
有些时候因为模型关联而发生。希望我的回答可以帮到你。
答案 1 :(得分:0)
您不想只添加虚拟字段吗?
可以在控制器中动态执行以下操作:
$this->Model->virtualFields['last_id'] = 'MAX(Model.id)';
以下是一个例子:
数据表“石斑鱼”:
mysql> select * from groupers;
+----+------+
| id | name |
+----+------+
| 1 | Jack |
| 2 | Jack |
| 3 | Mary |
| 4 | Kyle |
| 5 | Mary |
+----+------+
5 rows in set (0.00 sec)
GroupersController.php:
<?php
class GroupersController extends AppController {
public function index() {
$this->Grouper->virtualFields['last_id'] = 'MAX(Grouper.id)';
$data = $this->Grouper->find(
'all',
array(
'group' => array('Grouper.name')
)
);
$this->set('groupers', $data);
}
}
$ groupers输出:
Array
(
[0] => Array
(
[Grouper] => Array
(
[id] => 1
[name] => Jack
[last_id] => 2
)
)
[1] => Array
(
[Grouper] => Array
(
[id] => 4
[name] => Kyle
[last_id] => 4
)
)
[2] => Array
(
[Grouper] => Array
(
[id] => 3
[name] => Mary
[last_id] => 5
)
)
)
Cake生成的SQL:
SELECT `Grouper`.`id`, `Grouper`.`name`, (MAX(`Grouper`.`id`)) AS `Grouper__last_id` FROM `lt_events`.`groupers` AS `Grouper` WHERE 1 = 1 GROUP BY `Grouper`.`name`
(注意paginate只是扩展了find,所以功能不应该不同。)
答案 2 :(得分:0)
您的分页$option
应该像
$options = array(
'fields' => array('MAX(Model.id) as id','Model.name', 'Model.created'),
'order' => array( 'Model.created' => 'DESC'),
'group' => array('Model.name'),
'limit' => 20
);
然后应用其分页,
$this->paginate = $options;
接下来,
$result = $this->paginate('Model');
输出:
| id | name | created | modified |
----------------------------------------------------------
| 11 | test1 | 2014-11-28 14:05:39 | 2014-11-28 14:05:39 |
| 12 | test2 | 2014-11-28 14:05:39 | 2014-11-28 14:05:39 |
就是这样。
答案 3 :(得分:-1)
$this->paginate = array(
'limit' => 20,
'order' => array('Model.created' => 'DESC'),
'Conditions' => array (
'Model.id' => $this->Model->find ('list', array ('fields'=> array ('DISTINCT Model.name', 'Model.id'), 'order'=>'Model.created DESC'))
);