如何用CakePHP格式编写MySQL查询?

时间:2014-05-22 10:09:25

标签: mysql cakephp-2.0

我遇到了一个问题。 你能用cakephp格式写这个查询吗

表格

id   from_id  to_id  is_active  message
---  -------  -----  ---------  -------
 1     1        8       1       Hello
 2     8        1       1       Yes
 3     1        8       1       How are you?
 4     1        8       1       Are you with me?

代码:

<?php
    $qry = mysql_query("SELECT * FROM messages WHERE (from_id='8' OR  to_id='1') AND (from_id='1' OR  to_id='8') AND id_active='1'"));
    $res = mysql_fetch_array($qry);
?>

修改

我写过但是获得空值

我的代码:

$condition = array('OR'=>array('Message.from_id'=>1,'Message.to_id'=>8),'OR'=>array('Message.from_id'=>8,'Message.to_id'=>1),'Message.is_active'=>1);
$message=$this->Message->find("all",array('conditions'=>$condition));
pr($message);

输出:

array
(

)

2 个答案:

答案 0 :(得分:1)

如果你想列出对话,请试试这个:

 $this->Message->find('all' ,
            array(
                'conditions'=>array(
                    'AND'=>array(
                        'OR'=>array(
                        array('AND'=>array('from_id'=>1, 'to_id'=>'8')),
                        array('AND'=>array('from_id'=>8, 'to_id'=>'1'))
                        ),
                        'is_active'=>1
                    )
                )
            )

        );

好的查询是:

选择MessageidMessagefrom_idMessageto_idMessage。{{1} },is_activeMessage FROM messagec23dev1 AS messagess WHERE(((((Message = 1)AND({{ 1}} = 8)))OR(((from_id = 8)AND(to_id = 1)))))AND(from_id ='1'))

答案 1 :(得分:0)

我可以推荐使用Dogmatic69's converter。这为您的查询提供了此结果:

'conditions' => array(
    array(
        'or' => array(
            'from_id' => '8',
            'to_id' => '1',
        ),
    ),
    'id_active' => '1',
),

我不确定您的原始SQL查询实际上是在尝试返回什么,但如果您想要用户7和用户8之间的所有消息,那么您的查询应该是这样的:

SELECT * 
FROM messages 
WHERE ((from_id='7' AND to_id='8') OR (from_id='8' AND to_id='7'))
AND is_active='1';

这是SQLFiddle example

相关问题