0

我有一个 SQL 查询,我正试图将其转换为 CakePHP 查找,但我不知道如何构建它......有人可以提供一些帮助吗?

SELECT texts.*, people.id, people.first_name, people.last_name FROM texts 
    NATURAL JOIN (
         SELECT person_id, MAX(id) AS id
         FROM texts 
         WHERE texts.status = 'received' 
         GROUP BY person_id
    ) t RIGHT JOIN people ON people.id = t.person_id
    WHERE texts.body is not null
    AND texts.created > '$since'
    AND person.counselor_id = '2' 
    ORDER BY texts.created DESC

这是我所拥有的

    $texts = $this->find('all', array(
        'recursive' => -1,
        'joins' => array(
            array(
                'table' =>  'texts',
                'alias' =>  't',
                'type'  =>  'NATURAL',
                'conditions'    =>   array('t.status' => 'received')
            ),
            array(
                'table' => 'people',
                'alias' => 'Person',
                'type' => 'RIGHT',
                'conditions' => 'people.id = t.person_id'
            )   
        ),
        'conditions' => array('AND' => array('Text.body IS NOT NULL', 'Text.created > 0000-00-00 00:00:00')),
        'order' => 'Text.created DESC'
    ));

这是它编写的 SQL

SELECT Text.id, Text.person_id, Text.sid, Text.to, Text.from, Text.body, Text.status, 
     Text.direction, Text.owner, Text.counselor_read, Text.created, Text.modified 
FROM admissionsedge_penfield.texts AS Text 
NATURAL JOIN admissionsedge_penfield.texts 
AS t ON (t.status = 'received') 
RIGHT JOIN admissionsedge_penfield.people AS Person ON (people.id = t.person_id) 
WHERE ((Text.body IS NOT NULL) AND (Text.created > 0000-00-00 00:00:00)) 
ORDER BY Text.created DESC

谢谢!

4

1 回答 1

1

您是否定义了任何模型?如果是这样,您需要共享它们,以及您希望执行查找的那个,因为通常不使用右连接并且不使用自然连接

假设你不...

在控制器中,使用此代码运行上面的查询。{$recordset 分配行将是 find 方法通常所在的位置}

$some_sql = 'your sql statement';
$db = ConnectionManager::getDataSource('default');
$recordset = $db->rawQuery($some_sql);
set('recordset', $recordset);

如果您想利用 CakePHP 的 MVC,那么我建议将此查询重写为左连接和内连接

于 2013-09-28T01:46:06.560 回答