来自多个表的cakephp数据加入查询

时间:2013-08-12 18:12:16

标签: cakephp cakephp-2.0 cakephp-1.3

我正在开发Cakephp 2.x.我有这样的查询:

  $this->bindModel(array(
        'belongsTo' => array(
            'Contact' => array(
                'className' => 'Contact',
                'foreignKey' => false,
                'conditions' => array(
                    'Message.user_id = Contact.user_id',
                            array('Message.mobileNo' => array('Contact.mobileNo',
                           'Contact.workNo',
                            'Contact.homeNo',
                             'Contact.other')),
                ),

               'order'=>'Message.idTextMessage DESC',
            )
        )
    ), false);

    return $this->find('all', array('conditions' => array('Message.User_id' => $userid),
        'contain' => array('Contact' ),
        'fields' => array('Message.mobileNo',
            'Contact.mobileNo',
            'Contact.workNo',
            'Contact.homeNo',
            'Contact.other',
            'Contact.name',
            'Message.dateTime',
            'Message.type',
            'Message.body'),
        'group' => 'Message.mobileNo',
        'limit' => 6));
}

查询未按预期工作。好吧我弄清楚了问题。问题是当我打印这个查询时。它正在添加这个单引号('')('Contact.mobileNo')这样     和MessagemobileNo IN('Contact.mobileNo',                                  'Contact.workNo',                                  'Contact.homeNo',                                  'Contact.other'))

所以当我删除SQL yog中的引文时。查询有效。我的意思是我认为这部分中没有找到来自联系人的mobileno,workno等。任何人都知道我该怎么做?

好吧,如果你想看到简单的sql查询,这是完美的..在这里

          SELECT Message.mobileNo,
        Contact.mobileNo,
        Contact.workNo,
        Contact.homeNo,
        Contact.other,
        Contact.name,

        Message.body,
        Message.idTextMessage
   FROM cakephp_db.textmessage AS Message
   LEFT JOIN cakephp_db.contacts AS Contact ON Message.user_id = Contact.user_id
                                     AND Message.mobileNo IN (Contact.mobileNo,           Contact.workNo, Contact.homeNo, Contact.other)
 WHERE Message.User_id = 23
 GROUP BY Message.mobileNo
ORDER BY Message.idTextMessage DESC LIMIT 6

1 个答案:

答案 0 :(得分:2)

您应将其更改为:

$this->bindModel(array(
        'belongsTo' => array(
            'Contact' => array(
                'className' => 'Contact',
                'foreignKey' => false,
                'conditions' => array(
                    'Message.user_id = Contact.user_id',
                    '`Message`.`mobileNo` IN (`Contact`.`mobileNo`,`Contact`.`workNo`,`Contact`.`homeNo`,`Contact`.`other`)'),
                'order'=>'Message.idTextMessage DESC',
            )
        )
    ), false);

当您对条件使用键值时,蛋糕会将值视为字符串值而不是列名。