【问题标题】:How to get all associated information on relationship tables?如何获取关系表的所有相关信息?
【发布时间】:2012-02-24 20:47:24
【问题描述】:

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

<?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
)

为什么?我错过了什么?

【问题讨论】:

  • 尝试设置 $this->Information->recursive = 1;就行前读。您还可以/应该查看 CakePHP 书中的“可包含”行为。

标签: php cakephp frameworks


【解决方案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));
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多