2016-09-27 89 views
0

這是我的用戶表 enter image description here 這是我的留言表 enter image description here如何找到從消息表最後一條消息,也找到了用戶

,這是我的列表表格 enter image description here

現在我獲得成功用這個查詢得到最後一條消息

enter code here 
$coreQueryUser = $this->Message->query(' 
      select m.* 
      from 
       messages m 
       inner join (
       select max(id) as maxid 
       from messages 
       where messages.list_id = 3 
       group By (if(sender_id > reciever_id, sender_id, reciever_id)), 
       (if(sender_id > reciever_id, reciever_id, sender_id)) 
       ) t1 on m.id=t1.maxid 
     '); 

當我運行這個查詢時,它給了我foll由於輸出: -

enter code here 
<pre>Array 
(
[0] => Array 
    (
     [m] => Array 
      (
       [id] => 2 
       [sender_id] => 10 
       [reciever_id] => 21 
       [list_id] => 3 
       [message] => hello sir 
       [add_date] => 2016-09-25 08:24:38 
       [is_check] => 0 
      ) 

    ) 

[1] => Array 
    (
     [m] => Array 
      (
       [id] => 7 
       [sender_id] => 10 
       [reciever_id] => 22 
       [list_id] => 3 
       [message] => hmm 
       [add_date] => 2016-09-27 00:00:00 
       [is_check] => 0 
      ) 

    ) 
) 

現在您在第一陣列的輸出中看到SENDER_ID = 10和reciver_id = 21 和LIST_ID = 3 列表由用戶i希望獲取其編號爲10的輸出產生用戶ID爲21的用戶數據。請記住,當接收者將消息發送給發件人時,ID正在交換。在這種情況下我也想的用戶ID的數據是21

請幫我:(

回答

0

Finallly我找到我自己的

enter code here 
$coreQueryUser = $this->Message->query(' 
      select m.* ,u.* 
      from 
       messages m 
       inner join (
       select max(id) as maxid 
       from messages 
       where messages.list_id = " '. $data['list_id'] .'" 
       group By (if(sender_id > reciever_id, sender_id, reciever_id)), 
       (if(sender_id > reciever_id, reciever_id, sender_id)) 
       ) t1 on m.id=t1.maxid 
       join 
       users u ON u.id = (CASE WHEN m.sender_id = 10 
            THEN m.reciever_id 
            ELSE m.sender_id   
           END) 
     '); 
+0

請,這是{the_current_year}的解決方案,不直接將數據添加到查詢中,始終使用綁定!此代碼要求SQL注入攻擊。 – ndm

+0

感謝您的建議,請您提供從sql注入安全的代碼 – kunal

+0

http://book.cakephp.org/2.0/en/models/ retrieveing-your-data.html#prepared-statements,或將參數作爲第二個參數傳遞給query()方法。 – ndm

相關問題