我有一个表,其中列出了用户。那里有字段 id、Rating、Active。所以一个例子可以是:
id | rating | active | group (computed)
1 | 12 | 1 |
2 | 1 | 0 |
3 | 25 | 1 |
4 | 20 | 1 |
5 | 21 | 0 |
6 | 12 | 1 |
...
我的目标是使用其他计算组字段扩展这些字段。 我预计有 3 组用户。
- 事件字段中具有“0”的字段在组字段中具有“-”
这很简单,事件字段中带有“1”的用户将获得分配的两个组。
- 评分较高的“较好”一半用户将在组字段中获得 1
- 评级较差的“较差”一半用户将在组字段中获得 2
所以最终的计算表应该如下所示
id | rating | active | group (computed)
1 | 12 | 1 | 1
2 | 1 | 0 | -
3 | 25 | 1 | 2
4 | 20 | 1 | 2
5 | 21 | 0 | -
6 | 12 | 1 | 1
...
所以我有一个工作代码,但我认为必须编码得更好,但我不知道如何。
Controller 中的代码:
$this->paginate = [
'contain' => ['ExampleTableA', 'ExampleTableB']
];
$query = $this->Users->find('all')->order(['Users.first_name'=>'ASC', 'Users.last_name'=>'ASC']);
// Extending Group
$query->formatResults(function (\Cake\Datasource\ResultSetInterface $results) {
return $results->map(function ($row) {
if($row['active'] != 1){
$row['group'] = '-';
}
else{
$query_active = $this->UserParticipants->find('list', array('fields' => array('Users.id')))
->where(['Users.active' => 1])
->order(['Users.rating' => 'ASC','Users.id' => 'ASC']);
$array = $query_active->toList();
$length = $query_active->count();
$firsthalf = array_slice($array, 0, $length / 2);
$secondhalf = array_slice($array, $length / 2);
if(in_array($row['id'], $firsthalf)){
$row['group'] = 1;
}
if(in_array($row['id'], $secondhalf)){
$row['group'] = 2;
}
}
return $row;
});
});
$userParticipants = $this->paginate($query);
我的代码的问题是,$query_active
查找器将按照用户存在的数量执行。我无法在 map 功能中添加任何选项。
此示例代码来自此处:Adding Calculated Fields
那么你有什么改进或提示吗?
最佳答案
我对cakephp一无所知。但我认为您应该能够将 $firsthalf
和 $secondhalf
的计算移出匿名函数。
$this->paginate = [
'contain' => ['ExampleTableA', 'ExampleTableB']
];
$query = $this->Users->find('all')->order(['Users.first_name'=>'ASC', 'Users.last_name'=>'ASC']);
$query_active = $this->UserParticipants->find('list', array('fields' => array('Users.id')))
->where(['Users.active' => 1])
->order(['Users.rating' => 'ASC','Users.id' => 'ASC']);
$array = $query_active->toList();
$length = $query_active->count();
$firsthalf = array_slice($array, 0, $length / 2);
$secondhalf = array_slice($array, $length / 2);
// Extending Group
$query->formatResults(function (\Cake\Datasource\ResultSetInterface $results) use ($firsthalf, $secondhalf) {
return $results->map(function ($row) use ($firsthalf, $secondhalf) {
if($row['active'] != 1){
$row['group'] = '-';
}
else{
if(in_array($row['id'], $firsthalf)){
$row['group'] = 1;
}
if(in_array($row['id'], $secondhalf)){
$row['group'] = 2;
}
}
return $row;
});
});
$userParticipants = $this->paginate($query);
关于php - 在 cakephp 3 中构建困难的计算域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42102570/