根据CakePHP中的条件从两个表中获取数据

时间:2014-01-27 09:12:42

标签: php cakephp

我有两个控制器LeaveApplicationsController和EmployeesController。在LeaveApplicationsController索引操作中,我正在显示所有员工的休假记录。它显示正常,但我需要的是只显示登录员工离开该员工。我在leave_applications表中将employee_id作为外键。但我没有从employees表中获取employee_id(即id)。我还有用户表,每个用户都有一个与之关联的员工。因此,在创建员工时,在创建该用户之前,新创建的用户ID也存储在unser_id字段下的employees表中。因此,user_id是employees表中的外键,并唯一标识该员工。

这是我的LeaveApplicationsController.php代码: -

public function index()
    {
        $userId = $this->Auth->user('id'); //gets current user's id
        $this->LeaveApplication->recursive = 0;
        $leavereqs = $this->set('leaveApplications', $this->Paginator->paginate());
        $employeeId = $this->Employee->find('all', array('fields'=>array('id'), 'conditions'=>array('Employee.user_id'=>$userId))); // code for getting emp id
        return $this->LeaveApplication->find('all', array('conditions'=>array('LeaveApplication.employee_id'=>$employeeId))); //code for fetching current employee record
    }

但这显示错误。请告诉我,我在哪里做错了?我还使用$ uses在LeaveApplicationsController中加载Employee模型。感谢。

1 个答案:

答案 0 :(得分:0)

public function index()
    {
        $userId = $this->Auth->user('id'); //gets current user's id
        $this->LeaveApplication->recursive = 0;
        $leavereqs = $this->set('leaveApplications', $this->Paginator->paginate());
        $employeeId = $this->Employee->find('list', array('fields'=>array('id'), 'conditions'=>array('Employee.user_id'=>$userId))); // code for getting emp id
        return $this->LeaveApplication->find('all', array('conditions'=>array('LeaveApplication.employee_id'=>$employeeId))); //code for fetching current employee record
    }

find('all')将返回索引为Employee且id为

的数组

Imp链接:find('all'),find('first')和find('list')

http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-first

http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-all

http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list