CAKEPHP Mysql查询数据格式

时间:2014-01-18 18:34:51

标签: mysql cakephp

我已经在我的一个控制器方法中构建了这个查询 $students = $this->Student->query("SELECT id,name FROM students WHERE id IN (SELECT student_id FROM groups_students WHERE group_id = '$id') ");

我测试了它,我知道SQL返回正确的数据。在我看来,它与$this->Form->input('Student')

一起显示

我只是想让它打印出可以选择的学生的名字,这就是我选择名字和身份的原因......但是,在我的多选框中,它会打印出名称和由于某种原因,学生的身份以及“学生”这个词。

我希望以这种格式从SQL返回数据....

Array ( //[id] => 'displayValue',

[1] => 'displayValue1',
[2] => 'displayValue2',
[4] => 'displayValue4',
[5] => 'displayValue5',
[6] => 'displayValue6',
[3] => 'displayValue3',

这是从$this->Student->find('list').

返回数据的方式

目前,这是根据CakePHP文档在检索时格式化数据的方式。

array(
(int) 0 => array(
    'students' => array(
        'id' => '2',
        'name' => 'evan teague',
        'lesson_cost' => null,
        'paid_lessons' => null,
        'notes' => '',
        'created' => '2013-11-21 13:35:17',
        'modified' => '2014-01-13 22:31:14'
    )
),
(int) 1 => array(
    'students' => array(
        'id' => '3',
        'name' => 'Andrew',
        'lesson_cost' => null,
        'paid_lessons' => null,
        'notes' => '',
        'created' => '2013-11-22 10:08:01',
        'modified' => '2014-01-13 22:22:50'
    )
),
(int) 2 => array(
    'students' => array(
        'id' => '5',
        'name' => 'evan2',
        'lesson_cost' => null,
        'paid_lessons' => null,
        'notes' => '',
        'created' => '2013-11-22 14:17:57',
        'modified' => '2013-11-22 14:17:57'
    )
)

对此有任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

如果您收到了正确的数据,但显示时出现问题,请尝试以下操作:

在控制器中

$students = data from mysql query
$students = Hash::combine($students, '{n}.students.id', '{n}.students.name');
$this->set('students', $students);

在视图中:

echo $this->Form->input('Student', array(
   'options' => $students,
));

答案 1 :(得分:0)

   $options = array(
        'conditions'=>array('GroupsStudent.group_id'=>$id)
        'joins' => array(
            array(
                'alias' => 'GroupsStudent',  
                'table' => 'groups_students',
                'type' => 'LEFT',
                'conditions' => array(
                    'GroupsStudent.student_id'='Student.id',
                ),
            )
        ),
        'fields' => array('Student.id','Student.name')
    );
   $students = $this->Student->find('list',$options);

上述查询将返回id,名称对

的列表