CakePHP:连接表数据未在视图中显示

时间:2016-07-21 15:14:32

标签: php mysql sql cakephp

我有两个以hasMany / belongsTo关系链接的模型。这是hasMany定义:

//Table hr_emp_ids. Each employee can have many HR cases.
public $hasMany = array(
    'HrCase' => array(
        'className' => 'HrCase',
        'foreignKey' => 'emp_user_id'
        )
    );

这是belongsTo定义:

//Table hr_cases. Each HR case is owned by an employee.
public $belongsTo = array(
    'HrEmpId' => array(
        'className'=> 'HrEmpId',
        'foreignKey' => 'emp_user_id'
    );

我认为的控制器很简单:

public function view($id = null) {      
    $this->HrCase->id = $id;
    if (!$this->HrCase->exists()) {
        throw new NotFoundException(__('Invalid Case ID'));
    }
    $options = array('conditions' => array('HrCase.' . $this->HrCase->primaryKey => $id));
    $this->set('case', $this->HrCase->find('first', $options));
}

我尝试做的只是根据hr_cases.emp_user_id = hr_emp_ids = emp_user_id显示hr_emp_ids表中的hire_date和ssn。这是查看代码:

<tr>
<td><strong>Employee: </strong><br><?php echo h($case['HrCase']['full_name']); ?></td>
<td><strong>Date of Hire: </strong><br><?php echo h($case['HrEmpId']['hire_date']); ?></td>
<td><strong>SSN: </strong><br><?php echo h($case['HrEmpId']['ssn']); ?></td>

表格结构:

desc hr_emp_ids;
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| id          | int(11)     | NO   | PRI | NULL    | auto_increment |
| hire_date   | date        | YES  |     | NULL    |                |
| ssn         | varchar(11) | NO   |     | NULL    |                |
| emp_user_id | int(11)     | NO   |     | NULL    |                |
+-------------+-------------+------+-----+---------+----------------+

desc hr_cases; (truncated)
+--------------------+-------------+------+-----+---------+----------------+
| Field              | Type        | Null | Key | Default | Extra          |
+--------------------+-------------+------+-----+---------+----------------+
| id                 | int(11)     | NO   | PRI | NULL    | auto_increment |
| emp_user_id        | int(11)     | NO   |     | NULL    |                |

将显示HrEmpId模型中的任何内容。我不确定我在这里做错了什么。我已经做了很多次这样的协会,没有遇到任何麻烦。我可能会缺少什么?

1 个答案:

答案 0 :(得分:1)

我没有看到任何关联数据未显示的直接原因。你在这里找到代码

$options = array('conditions' => array('HrCase.' . $this->HrCase->primaryKey => $id));
$this->set('case', $this->HrCase->find('first', $options));

看起来可以使用getById()进行简化,因为$options中的唯一条件是检查$id。值得将Containable Behavior添加到HrCase模型,然后将getById()的第二个参数设置为true。这应该允许您准确指定返回的相关数据。

编辑:

在HrCase模型中,您与外键$belongsTo建立emp_user_id关系,但这不是hr_emp_ids中的主键。 这就是没有返回相关数据的原因。你需要设置这样的东西:

public $belongsTo = array(
    'HrEmpId' => array(
        'foreignKey' => false,
         'conditions' => array(
             'HrEmpId.emp_user_id = HrCase.emp_user_id'
         ),
    )
);

有关详情How to associate model in CakePHP by fields not named by convention?

,请参阅此处