使用Cakephp 1.3中的find('list')和自定义字段

时间:2014-11-06 10:52:58

标签: php cakephp

我正在使用cakephp 1.3项目。我在使用find('list')从我的数据库中检索一些数据时遇到问题。在我上次更改之前,我有这段代码:

$listaHabilidades = $this->Habilidad->find('list',array('fields'=>array('id','habilidad'),'order'=>array('habilidad'))));

这个命令给我下一个数组:

Array
(
    [40] =>  Bicicleta
    [42] =>  enganches de poleas
    [28] =>  Escalada
    [43] =>  transfer
    [41] => 4x4
    [53] => Administración Linux
    [72] => Ángeles
    [59] => Baile Flamenco
    [57] => Baloncesto
    [39] => Barranquismo
    [66] => Cante Flamenco
    [30] => Conducción
    [52] => Consola Linux
    [80] => cuarta prueba
    [75] => Demonios
    [84] => Esgrima
    [58] => Futbol
    [76] => Limpiar
    [77] => Limpiar2
    [54] => Linux
    [27] => Montañismo
    [60] => MS Office
    [65] => Natación
    [45] => Patinaje
    [56] => PC
    [78] => probar
    [44] => Programación
    [82] => Protocolo
    [81] => quinta prueba
    [63] => Tenis
    [79] => tercera prueba
    [83] => Triatlón
    [55] => W8
    [51] => XP
    [64] => Zapateado
)

但是我遇到了一个问题,因为数据可以在字段'habilidad'的开头有空格而我想要获取没有的数据并且没有它们也可以订购它们。所以我把命令改为:

$listaHabilidades = $this->Habilidad->find('list',array('fields'=>array('id','trim(Habilidad.habilidad)'),'order'=>array('trim(Habilidad.habilidad)'))));

它给了我下一个数组:

Array
(
    [41] => 
    [53] => 
    [72] => 
    [59] => 
    [57] => 
    [39] => 
    [40] => 
    [66] => 
    [30] => 
    [52] => 
    [80] => 
    [75] => 
    [42] => 
    [28] => 
    [84] => 
    [58] => 
    [76] => 
    [77] => 
    [54] => 
    [27] => 
    [60] => 
    [65] => 
    [45] => 
    [56] => 
    [78] => 
    [44] => 
    [82] => 
    [81] => 
    [63] => 
    [79] => 
    [43] => 
    [83] => 
    [55] => 
    [51] => 
    [64] => 
)

如何修剪列表(没有循环)?

2 个答案:

答案 0 :(得分:5)

您可以在模型中添加virtual field

public $virtualFields = array(
    't_habilidad' => 'LTRIM(Habilidad.habilidad)'
);

然后使用

$listaHabilidades = $this->Habilidad->find('list', array('fields'=>array('id','habilidad'), 'order' => array('t_habilidad'))));

答案 1 :(得分:1)

不完全确定CakePHP如何在内部生成查询,但您可以在检索后在php中修剪它

$listaHabilidades = $this->Habilidad->find('list',array('fields'=>array('id','habilidad'),'order'=>array('habilidad'))));
$listaHabilidades = array_map('trim', $listaHabilidades);

// voila