如何在cakephp中运行子查询

时间:2014-12-22 19:23:43

标签: php mysql cakephp

Cakephp 2.6

我有一个Model,Temps,它有很多票。在Temps的索引视图中,我想为每条记录返回一张日期最接近当前日期的票证。

在mySQL中,它可以作为

完成
'SELECT expiry_date FROM uploads WHERE expiry_date > CURDATE() ORDER BY expiry_date ASC LIMIT 1'

但我不知道如何将其作为子查询运行。我生成结果的当前查询如下:(记住这已经为数据表配置了)Tickets是上传模型的别名

 public function getAjaxIndexData($data) {
            $tokens = explode(" ", $data['searchString']);
            $conditions = array(
                $this->alias . '.deleted' => false,
                'OR' => array(
                    'CONCAT(' . $this->alias . '.first_name," ",' . $this->alias . '.last_name) LIKE' => '%' . implode(' ', $tokens) . '%',
                ),
                $data['columnsFilter']
            );
            $fields = array(
                'id',
                'full_name',
                'pps_number',
                'mobile',
                'email',
                'start_date',
                'time_served'
            );
            $order = array(
                $data['orderField'] => $data['order'] 
            );
            $contain = array(
                'LocalOffice.name',
            );

            $options = array(
                'conditions' => $conditions,
                'fields' => $fields,
                'order' => $order,
                'contain' => $contain,
                'limit' => $data['limit'],
                'offset' => $data['start']
            );
            $optionsNoFields = array(
                'conditions' => $conditions,
                'contain' => $contain,
            );

            $result['draw'] = $data['draw']; 
            $result['recordsTotal'] = $recordTotal = $this->find('count');
            $result['recordsFiltered'] = $this->find('count', $optionsNoFields); 
            $result['data'] = $this->find('all', $options); //standard search
            $result['data'] = $this->formatTable($result['data']); 

            return json_encode($result);
        }

在此查询中,我想添加一个字段,显示每个Temp的最近到期日期。

我将如何构建它?

1 个答案:

答案 0 :(得分:2)

动态创建虚拟字段:

$this->virtualFields['nearest'] = '(SELECT expiry_date FROM uploads WHERE expiry_date > CURDATE() AND uploads.owner_id = '.$this->alias.'.ticket_id  ORDER BY expiry_date ASC LIMIT 1')';

然后调整你的字段数组

        $fields = array(
            'id',
            'full_name',
            'pps_number',
            'mobile',
            'email',
            'start_date',
            'time_served',
            'nearest'
        );

此外,查询可以重写为(" temp"需要用模型别名替换)

SELECT MIN(expiry_date)
FROM uploads 
WHERE expiry_date > CURDATE()
  AND uploads.owner_id = temp.ticket_id;

这意味着可能性能更好的查询是将子查询从SELECT语句的列中移出到JOIN。例如:

SELECT * 
FROM temp
LEFT JOIN (SELECT MIN(expiry_date) AS expiry,owner_id
    FROM uploads 
    WHERE expiry_date > CURDATE())
    GROUP BY owner_id) AS next_dates
  ON next_dates.owner_id = temp.ticket_id;