cakephp包含按父模型值过滤 [英] cakephp contain filtering by parent model value

查看:76
本文介绍了cakephp包含按父模型值过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下关系:

出勤属于员工

计划属于员工

此find()可以很好地获取日期范围内的所有出勤记录。

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')
            )
    );

但是,此计划条件

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

获取当前计划。问题是员工在日期范围内有多个时间表。
为了获取有关其父母出勤记录的时间表,我还需要在Attendance.att_date

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

尝试

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

and

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

如何从contan Schedule条件中引用Attendance.att_date?那可能吗?
我当前的数据集很干净,我的find()很干燥,不想在这里弄乱。

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.

任何帮助都非常感谢。

推荐答案

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

When you use contain(), it does individual queries. In your example, it will actually do three queries individually that then get combined by CakePHP into the returned data array.

因此,您不能使用其他模型中的字段进行条件处理

So, you cannot use fields from a different model to condition against a contained model.

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

Your best bet is to either query the field first, then use it's value in this find, or use joins(), which makes all the results return from a single query instead of three separate queries.

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

Side note - it appears you're building this query in a Controller - following the MVC structure, best practice is to keep ALL queries in your Model, not your Controller - then just call the Model's method (which has the find()) from the Controller to retrieve the results.

这篇关于cakephp包含按父模型值过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆