Cakephp连接条件错误

时间:2014-04-30 11:26:12

标签: sql cakephp join conditional-statements

我有两张表employeesposting

employees包含字段idname

postings包含字段idemployee_idstatus

现在要检索Posting.status = 1的所有员工(包含发帖详情),我在PostingsController.php' view()行动中写道:

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

Employee.php模型中var $hasMany = 'Posting';

Posting.php模型中var $belongsTo = 'Employee';

但上面的代码会产生如下错误:

  

错误:SQLSTATE [42S22]:找不到列:1054未知列   ' Posting.status'在' where子句'

生成的SQL:

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

我是CakePhp加入的新手,请指导我。

1 个答案:

答案 0 :(得分:2)

当关系类型为hasMany时,Cake不会加入表。而是在第一个表(employees)上执行查询,并在员工的id上对postings表执行第二次查询,以检索与该员工相关的所有帖子

您可以手动加入表格,但我建议查询发布表格,然后按员工分组

$this->Posting ->find(
    'all',
    array(
        'fields' => array('Employee.id', 'Employee.name', 'Posting.status' ),
        'conditions' => $cond,
        'group' => array('Employee.id')
    )
);