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

如何以CakePHP格式编写MySQL查询?,mysql,cakephp-2.0,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

我遇到了一个问题。 你能用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);
?>
输出:

array
(

)
我可以推荐使用。为您的查询提供了以下结果:

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

这里有一个。

您好,如果您想列出对话,请尝试以下方法:

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

        );
好的查询是:


选择
Message
id
Message
from\u id,
Message
to\u id,
Message
处于活动状态,
Message
来自
c23dev1
消息作为
消息
其中((((
来自
=1)和(
to_id
=8)))或((
from_id
=8)和(
to_id
=1
))和(
处于活动状态
=1'))

它显示的是
从_id=8
到_id=1
的记录,但我还需要
的记录,我不明白。你的查询特别指出要包括:“
从\u id=8
到\u id=1
"。那么这是否意味着我的示例现在可以工作了?基本上,您是在尝试显示用户7和8之间的所有消息,还是向用户7发送/从用户7发送的所有消息以及向用户8发送/从用户8发送的所有消息,而不管它们是否相互发送?是的@Cylindric我想显示彼此之间的对话。那么您的原始SQL是错误的。请使用我的示例我的回答。这给出了所有消息“从A到B”和所有消息“从B到A”。使用
消息中的一些示例输入和您希望看到的输出更新您的问题。您的示例查询应该返回哪些记录?因为如果我运行您的示例SQL,它也不会返回任何内容。您的基本SQL可能有错?您的示例中没有一个
to\u id
of
from\u id
的值为1,因此您的示例减少了到
从\u id=8到\u id=8
 $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
                    )
                )
            )

        );