2017-07-03 62 views
2

我需要使用cake php方法來構建此自定義查詢,但可以使這個子查詢以蛋糕擱淺的方式嗎?加入語句中的PHP3子查詢

SELECT 
        m.chat_id AS chat_id, 
        m.message AS message, 
        m.created AS created, 
        g.title AS title, 
        u.id AS id, 
        u.name AS name, 
        g.id AS gig_id 
        FROM message m 
        NATURAL JOIN (
        SELECT chat_id, MAX(id) AS id 
        FROM  message 
        GROUP BY chat_id 
       ) t 
        RIGHT JOIN chat c ON c.id = t.chat_id 
        INNER JOIN application a ON a.chat_id = m.chat_id 
        INNER JOIN gig g ON g.id = a.gig_id 
        INNER JOIN user u ON u.id = a.user_id 
        WHERE (g.status = 1) 
        ORDER BY m.created DESC 

我的代碼是一樣的東西下面

$this->loadModel('Message'); 
     $dataField = $this->Message->find() 
      ->hydrate(false) 
      ->select(['Message.chat_id', 'Message.message', 'Message.created', 'u.id', 'u.name', 'g.id']) 
      ->join([ 
       'a' => [ 
        'table' => 'application', 
        'type' => 'INNER', 
        'conditions' => 'a.chat_id = chat_id', 
        ], 
       'g' => [ 
        'table' => 'gig', 
        'type' => 'INNER', 
        'conditions' => 'g.id = a.gig_id', 
        ], 
       'u' => [ 
        'table' => 'user', 
        'type' => 'INNER', 
        'conditions' => 'u.id = a.user_id', 
       ], 

      ]) 
      ->where(['g.status' => 1]) 
      ->order(['Message.created' => 'DESC']); 

我需要知道實現

NATURAL JOIN (
        SELECT chat_id, MAX(id) AS id 
        FROM  message 
        GROUP BY chat_id 
       ) t 
        RIGHT JOIN chat c ON c.id = t.chat_id 

蛋糕的方式。謝謝。

回答

4

你可以試試嗎? Natural Join不會在這裏工作。我會稍後看看。謝謝。

$this->loadModel('Message'); 
$query = $this->Message->find() 
    ->hydrate(false) 
    ->select([ 
     'Message.chat_id', 
     'Message.message', 
     'Message.created', 
     'u.id', 
     'u.name', 
     'g.id', 
     't.id', 
     't.chat_id' 
    ]) 
    ->join([ 
     'a' => [ 
      'table'  => 'application', 
      'type'  => 'INNER', 
      'conditions' => 'a.chat_id = Message.chat_id', 
     ], 
     'g' => [ 
      'table'  => 'gig', 
      'type'  => 'INNER', 
      'conditions' => 'g.id = a.gig_id', 
     ], 
     'u' => [ 
      'table'  => 'user', 
      'type'  => 'INNER', 
      'conditions' => 'u.id = a.user_id', 
     ], 
     't' => [ 
      'table'  => '(SELECT chat_id, MAX(id) AS id FROM message GROUP BY chat_id)', 
      'type'  => 'INNER', 
      'conditions' => 't.id > 0', 
     ], 
     'c' => [ 
      'table'  => 'chat', 
      'type'  => 'RIGHT', 
      'conditions' => 'c.id = t.chat_id', 
     ] 
    ]) 
    ->where(['g.status' => 1]) 
    ->order(['Message.created' => 'DESC']); 

$this->loadComponent('Paginator'); 
$paginated = $this->Paginator->paginate($query, ['limit' => 2]); 
pr($paginated); 
die; 
+0

感謝您的解決方案,它顯示的路徑,但我需要爲我的問題實施'自然聯接'。有什麼辦法可以在CakePHP3中實現'Natural Join'? 我可以在下面的方式做到這一點,但沒有'條件'可能嗎? 't'=>''''''''''(SELECT chat_id,MAX(id)AS id FROM message GROUP BY chat_id)', 'type'=>'Natural', ] – Miuranga