Question

I have two tables employees and posting.

employees with fields id,name

AND

postings with fields id,employee_id,status

Now to retrieve all the employees(with posting details) whose Posting.status = 1, I wrote in PostingsController.php's view() action:

$cond = array('Posting.status'=>1);
$e = $this->Employee->find('all',array('conditions' => $cond));
$this->set('emp',$e);

In Employee.php model var $hasMany = 'Posting';

In Posting.php model var $belongsTo = 'Employee';

But the above code generates an error like :

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Posting.status' in 'where clause'

Generated SQL:

SQL Query: SELECT `Employee`.`id`, `Employee`.`name` FROM `cakelab`.`employees` AS `Employee` WHERE `Posting`.`status` = 1 

I am new to CakePhp joins, please guide me.

Was it helpful?

Solution

Cake doesn't join the tables when the relation type is hasMany. Rather it performs a query on the first table (employees) and with the id of the employee it performs a second query on postings table to retrieve all the postings related to that employee

you can manually join the tables but I suggest querying on postings table and then group by Employee

$this->Posting ->find(
    'all',
    array(
        'fields' => array('Employee.id', 'Employee.name', 'Posting.status' ),
        'conditions' => $cond,
        'group' => array('Employee.id')
    )
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top