如何获取关系表的所有相关信息?

时间:2012-02-24 20:47:25

标签: php cakephp frameworks

我有一些相关的表格,主要是模型:

<?php
App::uses('AppModel', 'Model');
class Information extends AppModel {
public $useTable = 'informations';
public $displayField = 'name';
public $validate = array(
    'name' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'The field name can not be empty',
        ),
    ),
    'lastname' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'The field lastname can not be empty',
        ),
    ),
    'email' => array(
        'email' => array(
            'rule' => array('email'),
            'message' => 'The email address is not correct',
        ),
    ),
);

public $belongsTo = array(
    'Country' => array(
        'className' => 'Country',
        'foreignKey' => 'countries_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

public $hasMany = array(
        'Education' => array(
                'className' => 'Education',
                'foreignKey' => 'informations_id',
                'dependent' => true
        ),
        'Experience' => array(
                'className' => 'Experience',
                'foreignKey' => 'informations_id',
                'dependent' => true
        ),
        'Attachment' => array(
                'className' => 'Attachment',
                'foreignKey' => 'informations_id',
                'dependent' => true
        )
);

}

我需要获取与ID相关的所有数据,但是当我尝试使用此代码获取数据时:

  public function view($id = null) {
    $this->Information->id = $id;
    if (!$this->Information->exists()) {
        throw new NotFoundException(__('Invalid information'));
    }
    $this->set('information', $this->Information->read(null, $id));
}

表格“教育,经验和附件”中的信息不会仅显示此信息:

Array
(
   [id] => 9
   [name] => Reynier
   [lastname] => Perez Mira
   [email] => reynierpm@gmail.com
   [mobile_phone] => 04241805609
   [home_phone] => 02735555899
   [address] => asdas
   [picture] => skills.png
   [other_information] => asdasdasd
   [recruitment_status] => Call for Interview
   [countries_id] => 9
)

为什么呢?我错过了什么?

1 个答案:

答案 0 :(得分:1)

更新您的函数以在信息上设置递归:

public function view($id = null) {
    $this->Information->id = $id;
    if (!$this->Information->exists()) {
        throw new NotFoundException(__('Invalid information'));
    }
    $this->Information->recursive = 1;
    $this->set('information', $this->Information->read(null, $id));
}

然后确保您的信息模型中的所有关系都设置为指向您要包含的其他模型。