Alb*_*ert 2 php cakephp cakephp-2.2 cakephp-model
我想在下拉列表中显示所有项目负责人的姓名.
项目负责人只是在公司工作的一些员工.
这是我的表格:
project_leaders
,----,----------------,
| id | hr_employee_id |
|----|----------------|
| 1 | 18 |
'----'----------------'
projects
,----,------,-------------------,
| id | name | project_leader_id |
|----|------|-------------------|
| 1 | cake | 1 |
'----'------'-------------------'
hr_employees
,----,------,---------,
| id | name | surname |
|----|------|---------|
| 18 | joe | dirt |
'----'------'---------'
Run Code Online (Sandbox Code Playgroud)
我的ProjectsController看起来像这样:
public function add() {
if ($this->request->is('post')) {
$this->Project->create();
if ($this->Project->save($this->request->data)) {
$this->_sendProjectRequestEmail($this->Project->getLastInsertID() );
$this->Session->setFlash(__('The project has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The project could not be saved. Please, try again.'));
}
}
$this->set('projectLeaders',$this->Project->ProjectLeader->find('list');
}
Run Code Online (Sandbox Code Playgroud)
这只返回项目负责人的ID,而不是名称和姓氏.因此,而不是Joe Dirt,它返回1.
我已经尝试过$ this-> Project-> ProjectLeader-> HrEmployee-> find('list')但列出了所有员工.
我也试过指定字段,但它返回一个未知的字段错误.
我究竟做错了什么?
$this->set('projectLeaders',$this->Project->ProjectLeader->find('list'));
Run Code Online (Sandbox Code Playgroud)
这将只列出表中的记录,project_leaders很可能,因为表本身不包含名称/标题字段(哪个蛋糕会自动拾取displayField)如下所示:
array(
1 => 1
)
Run Code Online (Sandbox Code Playgroud)
为了让项目负责人的有意义的名单,你需要确保你之间的一个连接project_leaders和hr_employees一个办法做到这一点是使用中可容纳的行为和简单地指定哪些字段列表中的使用方法:
$projectLeaders = $this->Project->ProjectLeader->find('list', array(
'contain' => array(
'HrEmployee'
),
'fields' => array(
'ProjectLeader.id',
'HrEmployee.name',
)
));
$this->set(compact('projectLeaders'));
Run Code Online (Sandbox Code Playgroud)
有一个表相当于说"这个用户是管理员"的表可能不是最好的想法 - 如果表project_leaders(仅)是hr_employees表上的一个布尔字段并且project_leader_id指向的话,那么避免数据问题会更容易,并且给你更简单的查询该hr_employee表中,没有一些其他的数据抽象.
当然我不知道你的整个架构,很可能是一个单独的project_leaders表的一个很好的理由.
如果您添加名称字段project_leaders- 您不需要联接来了解项目负责人的姓名或任何funkiness:
alter table project_leaders add name varchar(255) after id;
update project_leaders set name = (select name from hr_employees where hr_employees.id = hr_employee_id);
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以通过一个查询/加入知道谁是相关项目负责人,而不需要进行两次联接来获取员工的姓名.