0

当我对其设置条件时,我无法从第三个表中获取记录。我收到错误缺失列 MonthlyReturns 缺失。但是如果我去掉 MonthlyReturns 条件,我会得到所有 3 个关联的表。

这些表是公司、员工和月度回报

我在 MonthlyReturnsController.php 中的查找代码:

$conditions = array("Employee.active" => true, "Employee.start" => $start, "NOT" => array("MonthlyReturn.month" => $date));
$empl = $this->MonthlyReturn->Employee->find('all', array('conditions' => $conditions));

员工模型:

/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
    'Company' => array(
        'className' => 'Company',
        'foreignKey' => 'company_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

/**
* hasMany associations
*
* @var array
*/
public $hasMany = array(
    'MonthlyReturn' => array(
        'className' => 'MonthlyReturn',
        'foreignKey' => 'employee_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);

更新:

我试图做一个左连接。现在我取回了所有记录,并且没有显示该日期在 MonthlyReturns 中没有记录的员工。

我得到的sql是

[query] => SELECT `Employee`.`id`, `Employee`.`company_id`,`Employee`.`p45_issued`, `Company`.`id`, `Company`.`member_number`
FROM `employees` AS `Employee` 
left JOIN `monthly_returns` AS `MonthlyReturn` ON (`MonthlyReturn`.`employee_id` = `Employee`.`id`) 
LEFT JOIN `companies` AS `Company` ON (`Employee`.`company_id` = `Company`.`id`) 
WHERE NOT (`MonthlyReturn`.`month` = '2013-03-01')

$options['joins'] = array(
    array('table' => 'monthly_returns',
        'alias' => 'MonthlyReturn',
        'type' => 'left',
        'conditions' => array(
            'MonthlyReturn.employee_id = Employee.id'
        )
    ),
);

$options['conditions'] = array("Employee.p45_issued" => false, "NOT" => array("MonthlyReturn.month" => $last_month));


$empl = $this->MonthlyReturn->Employee->find('all', $options);

更新 2

我已经设法通过直接使用 sql 来获取我想要的记录。我不喜欢这样做,所以如果有人知道正确的 cakephp 方式?

    $emps_overdue = $this->Employee->query("SELECT employees.*, companies.`name`, companies.`id`

    FROM employees INNER JOIN companies ON employees.company_id = companies.id

    LEFT JOIN monthly_returns ON monthly_returns.employee_id = employees.id

    AND monthly_returns.month = '$last_month'

    WHERE monthly_returns.id IS NULL AND employees.p45_issued = false");
4

1 回答 1

0

尝试研究可包含的行为,这将使您的任务更容易。

于 2013-03-09T05:33:26.627 回答