cakephp nest array从sub到sub关系

时间:2014-08-02 22:44:45

标签: cakephp find multidimensional-array

我需要以下格式的4个表的结果

array(
       (int)0=>array(
              'Fee'=>array(
                     'id'=>'1',
                     'student_id'=>array(
                                   'id'=>'22',
                                    'name'=>'Jhon',
                                    'age'=>'15',
                                    'class_id'=>array(
                                               'id'=>'6',
                                               'class'=>'4th',
                                                ....
                                                ),
                                     ......
                                     ),
                       'paid'=>'2000',
                       'date'=>'2014-11-11 11:11:11',
                       'user_id'=>array(
                                  'id'=>'3',
                                  'name'=>'Smith',
                                   ....
                                   )
                      )
       )
 )

表明智的

fee.id, fee.paid, 
student.id,student.name,
class.name,
user.name

表格结构和关联

fees(id,student_id,paid,date,...,user_id)

链接到学生和用户表

students(id,user_id,class_id,....)

链接到用户表

classes(id,name,....)

属于学生

users(id,name,email,password,age,role....)

部分属于学生   有些记录是供管理员登录的   虽然有些属于学生bcz,但他们也需要登录

我厌倦了尝试加入,包含,线程
我怎样才能得到所需的结果

1 个答案:

答案 0 :(得分:0)

假设您的表和模型遵循了正常的命名约定,并且您之间正确设置了关系,然后执行以下操作:

$fees = $this->Fee->find('all',
    array(
        'fields' => array(
            'Fee.id',
            'Fee.paid',
            'Fee.date'
        ),
        'contain' => array(
            'Student' => array(
                'fields' => array(
                    'Student.id',
                    'Student.name',
                    'Student.age',
                ),
                'contain' => array(
                    'Class' => array(
                        'fields' => array(
                            'id',
                            'class'
                        )
                    )
                )
            ),
            'User' => array(
                'fields' => array(
                    'id',
                    'name'
                )
            )
        )
    )
);

会产生:

$fees = array(
    (int)0 => array(
        'Fee' => array(
            'id' => 1,
            'paid' => '2000',
            'date' => '2014-11-11 11:11:11',
            'Student' => array(
                'id' => 22,
                'name' => 'John',
                'age' => '15',
                'Class' => array(
                    'id' => 6,
                    'class' => '4th'
                )
            ),
            'User' => array(
                'id' => 3,
                'name' => 'Smith'
            )
        )
    ),
    (int)1 => //next Fee
);

如果您仍然需要完全按原样放置数组,那么使用php进行数组重组并不会太复杂。

P.S您需要在您设置的学生,班级和用户模型上进行此操作:

public $actsAs = array('Containable');

为了包含'要运行的部分查询:)