1

我不知道工作人员参加课程和集会的时间总和的结果。这是我的数据库:-

staffs
+---+-------+-----------+
| id| Name  | Department|
+---+-------+-----------+
| 1 | Joe   | HR        |
| 2 | Andra | Support   |
| 3 | Khan  | HR        |
| 4 | Toll  | HR        |
| 5 | Gosh  | Support   |
| 6 | Rama  | Support   |
+---+-------+-----------+



attendances
+---+---------+-----------+--------------+
|id | name_id | course_id | assembly_id  |
+---+---------+-----------+--------------+
| 1 |    1    |  101      |              |
| 2 |    1    |  102      |              |
| 3 |    1    |           | 501          |
| 4 |    2    |  102      |              |
| 5 |    3    |           | 502          |
| 6 |    3    |  103      |              |
| 7 |    4    |  101      |              |
| 8 |    4    |           | 501          |
| 9 |    4    |  102      |              |
+---+---------+-----------+--------------+    


courses
+-------+-----------+-------+
| id    | name      | hours |
+-------+-----------+-------+
| 101   | courses_1 | 8     |
| 102   | courses_2 | 6     |
| 103   | courses_3 | 9     |
+-------+-----------+-------+


assembly
+-------+---------------+-------+
| id    | name          | hours |
+-------+---------------+-------+
| 501   | assembly_1    | 2     |
| 502   | assembly_2    | 4     |
+-------+---------------+-------+

在“模型”>“出勤”中,我已经添加了一个关系:-

public $belongsTo = array('Staff','Course','Assembly'); 

在我的控制器中,我尝试编写以下代码:-

$view = $this->Staff->find('all',array(
'fields' => array('SUM(COALESCE(Course.hours,0))+SUM(COALESCE(Assembly.hours,0)) as ec_count'),'recursive'=>2));
$this->set('view', $view); 

但它会返回一个错误..(好像我在这里做错了)

如何在这种情况下编写代码,它将通过如下视图显示:-

+---+-------+-----------+------------+
| id| Name  | Attend    | Total Hour |
+---+-------+-----------+------------+
| 1 | Joe   | course_1  |      16    |
|   |       | course_2  |            |
|   |       | assembly_1|            |
| 2 | Andra | course_2  |       6    |
| 3 | Khan  | assembly_2|      13    |
|   |       | course_3  |            |
| 4 | Khan  | course_1  |      16    |
|   |       | assembly_1|            |
|   |       | course_2  |            |
| 5 | Gosh  | -         |      0     |
| 6 | Rama  | -         |      0     |
+---+-------+-----------+------------+
4

1 回答 1

0

除非您正在执行 Joins(请参阅CakePHP Joins),否则您将无法获得这样的 SUM,因为 CakePHP 将实际运行单个查询,然后组合并返回数据。

我认为最好的办法是跟踪“员工”表中的总小时数Staff.course_hours和字段。Staff.assembly_hours您仍然可以将各个行保留在Assembly.hoursandCourse.hours中,然后在afterSave()(请参阅 CakePHP afterSave)回调(或类似的东西)上更新 Staff hours 字段。

然后,您可以只设置一个名为的虚拟字段(请参阅CakePHP Virtual Fieldstotal_hours,您可以根据需要对其进行排序、显示或使用。

或者,您可以构建联接并在单个(尽管稍微复杂一点)查询中完成。

于 2012-12-05T01:11:08.270 回答