Question

I am working on a Cakephp 2.x. I have a query like this:

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

The query is not working as expected. well I figure out the problem .The problem is when I print this query.It is adding this single quotation (' ') around ('Contact.mobileNo') like this AND Message.mobileNo IN ('Contact.mobileNo', 'Contact.workNo', 'Contact.homeNo', 'Contact.other'))

So when I remove the quotations in SQL yog. The query works. I mean I think it is not finding the mobileno,workno, etc from contacts here in this part. Any one know what should I do?

well if you want to see the simple sql query which is working perfect.. is here

          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
Was it helpful?

Solution

You should change it to:

$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);

when you use key-value for conditions , cake consider value as string value not a column name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top