Fra*_*uke 13 cakephp distinct find cakephp-1.2
我正在写一个CakePHP 1.2应用程序.我有一个人员列表,我希望用户能够在不同的字段上进行过滤.对于每个可过滤的字段,我有一个下拉列表.选择过滤器组合,单击过滤器,页面仅显示匹配的记录.
在people_controller中,我有一些代码:
$first_names = $this->Person->find('list', array(
'fields'=>'first_name',
'order'=>'Person.first_name ASC',
'conditions'=> array('Person.status'=>'1')
));
$this->set('first_names', $first_names);
Run Code Online (Sandbox Code Playgroud)
(状态= 1,因为我使用的是软删除.)
这将创建所有first_names的有序列表.但重复是在那里.
在Cookbook中,我找到了一个使用DISTINCT关键字并修改我的代码来使用它的示例.
$first_names = $this->Person->find('list', array(
'fields'=>'DISTINCT first_name',
'order'=>'Person.first_name ASC',
'conditions'=> array('Person.status'=>'1')
));
Run Code Online (Sandbox Code Playgroud)
这给了我一个像这样的SQL错误:
Query: SELECT `Person`.`id`, DISTINCT `Person`.` first_name` FROM `people` AS `Person` WHERE `Person`.`status` = 1 ORDER BY `Person`.`first_name` ASC
Run Code Online (Sandbox Code Playgroud)
问题很明显.该框架将Person.id添加到查询中.我怀疑这来自使用'list'.
单击过滤器按钮时,我将使用选定的过滤器创建SQL语句.我不需要is字段,但无法摆脱它.
谢谢Frank Luke
小智 24
尝试使用'group by',它的作用是完美的:
$first_names = $this->Person->find('list', array(
'fields'=>'first_name',
'order'=>'Person.first_name ASC',
'conditions'=> array('Person.status'=>'1'),
'group' => 'first_name'));
Run Code Online (Sandbox Code Playgroud)
Mar*_*rko 19
你说得对,看来你不能用DISTINCT
同list
.由于您不需要id
但只需要名称,您可以find all
像上面那样使用$first_names = Set::extract($first_names, '/Person/first_name');
.这将为您提供一个具有不同名字的数组.
以下是我在 CakePHP 3.x 中的做法:
$query = $this->MyTables->find('all');
$result = $query->distinct()->toArray();
Run Code Online (Sandbox Code Playgroud)
小智 5
你可以试试这个.这里将Person id作为键,因此没有重复输入的机会.
$first_names = $this->Person->find('list', array(
'fields' => array('id','first_name'),
'conditions' => array('Person.status' => '1'),
));
$this->set('first_names', $first_names);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41957 次 |
最近记录: |