我的选择列表显示ID不是值,CakePHP

时间:2014-10-06 01:39:47

标签: php cakephp cakephp-model

如何在选择列表中获取类别名称而不是其ID? ,我正在使用CakePHP

'类别' table只有两列(id,name)

视图部分:

echo $this->Form->input('category',array(
                                             'type' => 'select', 
                                             'options' => $categories,   
                                             'empty' => 'select category'        
                                        ));

协会:

class Job extends AppModel{
public $name = 'Job';
public $belongsTo = array('Category');
}

和控制器:

$categories= $this->Job->Category->find('list');
$this->set('categories',$categories);  

结果是一个包含1,2,3,4,5,6值的选择列表

3 个答案:

答案 0 :(得分:1)

您需要编辑控制器代码,如下所示:

$categories= $this->Job->Category->find('list',array('fields'=>array('Category.id','Category.name')));

答案 1 :(得分:0)

你需要在cakephp中使用虚拟字段。

http://book.cakephp.org/2.0/en/models/virtual-fields.html

也是ctp文件中的Line main

foreach($times as $key => $value ){ $timesList[$value] = $value; } $times = $timesList

根据您的模型控制器使用。对于mor信息。请点击此链接。我面临同样的问题,我得到了解决方案。

virtual field are not working in cakephp

答案 2 :(得分:0)

在cakephp 3.X中

// Common Usage:
$users = [
    ['id' => 1, 'name' => 'mark'],
    ['id' => 2, 'name' => 'jane'],
    ['id' => 3, 'name' => 'sally'],
    ['id' => 4, 'name' => 'jose'],
];
$results = Hash::extract($users, '{n}.id');
// $results equals:
// [1,2,3,4];

https://book.cakephp.org/3.0/en/core-libraries/hash.html