0

I have these relations:

Attendance belongs to Employee

Schedule belongs to Employee

This find() works just fine to get all Attendance records in a date range.

    $data = $this->Attendance->find('all', array(
        'contain' => array(
            'Employee' => array(
                'Schedule' => array(
                    'conditions' => array('sche_status' => 1),
                    'order' => 'sche_valid DESC',
                    'limit' => 1
            ))
        ),
        'conditions' => $conditions,
        'order' => array('employee_id', 'att_date')
            )
    );

However, this Schedule condition

'conditions' => array('sche_status' => 1),

gets the "current" Schedule. Problem is when Employee has more than one Schedule in the date range. In order to get the relevant Schedule for it's parent Attendance record, I need to also condition on Attendance.att_date

Tried

'conditions' => array('sche_status' => 1, 'ho_valid <=' => Attendance.att_date)

and

'conditions' => array('sche_status' => 1, 'ho_valid <=' => $this->Attendance.att_date)

How can I reference Attendance.att_date from the contan Schedule conditions? Is that possible? My current datasets are pretty clean and my find() is dry, wouldn't want to make a mess here.

Any help greatly appreciated.

4

1 回答 1

0

当您使用contain()时,它会执行单独的查询。在您的示例中,它实际上会分别执行三个查询,然后由 CakePHP 组合到返回的数据数组中。

因此,您不能使用来自不同模型的字段来针对包含的模型进行条件处理。

您最好的选择是先查询该字段,然后在此查找中使用它的值,或者使用joins(),这使得所有结果都从单个查询而不是三个单独的查询返回。

旁注-您似乎正在控制器中构建此查询-遵循 MVC 结构,最佳做法是将所有查询保留在您的模型中,而不是您的控制器中-然后只需find()从控制器调用模型的方法(具有 )即可检索结果。

于 2012-11-30T02:13:57.790 回答