2012-07-07 44 views
0

我的應用我有我的消息模型的方法,它返回被當前用戶($ ID)發送的消息。它使用3個連接從3個表中返回信息。發送者和接受者來自相同的「用戶」表兩種,我不得不別名這些列。的Zend Framwork選擇()給出了意外的SQL

方法在我的消息模型:

public function getSentMessages($id) 
{ 
    $messageModel = new self(); 
    $select = $messageModel->select() 
       ->from(array('m' => 'messages'), 
         array('m.id', 'm.title', 'm.send', 
           's.id AS s_id', 's.firstname AS s_fn', 's.lastname AS s_ln', 's.email AS s_e', 
           'r.id AS r_id', 'r.firstname AS r_fn', 'r.lastname AS r_ln', 'r.email AS r_e')) 
       ->join(array('s' => 'users'), 
         'm.from = s.id') 
       ->join(array('mu' => 'messages_users'), 
         'm.id = mu.message_id') 
       ->join(array('r' => 'users'), 
         'r.id = mu.user_id') 
       ->where('m.from = ?', $id); 


    $select->setIntegrityCheck(false); 
    $messages = $messageModel->fetchAll($select); 

    return $messages; 
} 

奇怪的事情發生的地方:在resultrow是做出來會要求我的所有列的......但不知何故,所有列(includuding我沒」的那些t請求)之後添加。就像這樣:

id title send s_id s_firstname  s_lastname s_email  r_id r_firstname  r_lastname r_email  id username password firstname lastname email role id message_id user_id  status id username password firstname lastname email role 

我發現通過Zend框架返回的SQL查詢是不是我多麼希望它是..這是(清理可讀性更好):

SELECT m.id, m.title, m.send, 
s.id AS s_id, s.firstname AS s_fn, s.lastname AS s_ln, s.email AS s_e, 
r.id AS r_id, r.firstname AS r_fn, r.lastname AS r_ln, r.email AS r_e, 
s. * , mu. * , r. * 
FROM messages AS m 
INNER JOIN users AS s ON m.from = s.id 
INNER JOIN messages_users AS mu ON m.id = mu.message_id 
INNER JOIN users AS r ON r.id = mu.user_id 
WHERE (
m.from = '12345' 
) 

檢查這些asterixes(*)在我的SELECT語句的結束..怎麼這些到達那裏?在Zend單證告訴我沒有給出列時,一個星號僅用於..

感謝您的幫助!

回答

2

加入有三個參數:

添加一個空值,@每一個加入條款的結束..

join(array('s' => 'users'),'m.from = s.id','') 
+0

非常感謝!我認爲這些可選的「*」不是默認值。問題解決了 – 2012-07-07 13:26:41

+0

很高興能幫助你。如果您認爲它有幫助,請不要忘記接受答案;) – 2012-07-07 13:28:03

+1

爲了代替添加空白值,我將相關列從from子句移到了join子句,非常整齊。 – 2012-07-07 13:29:27