Zend Framework select()给出了意想不到的SQL

时间:2012-07-07 13:14:12

标签: php mysql sql zend-framework zend-db

对于我的应用程序,我在Messages模型中有一个方法,它返回当前用户发送的所有消息($ id)。它使用3个连接返回3个表中的信息。由于发件人和收件人都来自相同的“用户”表,因此我必须为这些列添加别名。

我的消息模型中的方法:

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;
}

奇怪的事情发生了:结果是由我要求的所有列中提出的...但不知何故所有列(包括我没有请求的列)之后添加。像这样:

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 Framework返回的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'
)

在我的SELECT语句末尾检查这些星号(*)..这些是如何实现的? Zend文档告诉我,只有在没有给出列时才使用asterix。

谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

Join有三个参数:

在每个Join子句的末尾添加一个空白值..

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