0

CakePHP の検索結果に変換しようとしている SQL クエリがありますが、それを構造化する方法がわかりません... 誰かが少し助けてくれませんか?

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 に答える