如何在cakephp中编写一个引用不同表的mysql查询

时间:2014-03-26 07:12:04

标签: cakephp

我有表USERS(id,email),MAIL(id,message,receiver,user_id),SERVICES(id,service,user_id)......

用户发布服务,另一个用户通过邮件回复该服务。我想写一个查询,它将检索从USERS发布该特定服务的用户的电子邮件,并在有人回复该服务时在MAIL的接收者字段中捕获它。

我很擅长蛋糕,不知道从哪里开始

$receiver = $this->User->find('first',array(
             'conditions' => array(
                     'Users.user_id' => 'Services.user_id', 
              )
));

SQL Query

SELECT u.email FROM users AS u, services AS s WHERE s.user_id = u.id LIMIT 0 , 30

1 个答案:

答案 0 :(得分:0)

假设您有User.php模型,请创建一个操作,如下所示

function getData(){
$options = array(
        //'conditions' => array(‘User.user_id’=>9),
        'joins' => array(
            array(
                'alias' => 'Service',  
                'table' => ‘services’,
                'type' => 'LEFT',
                'conditions' => array(
                    'Service.user_id = User.id',
                ),
            ),
            array(
                'alias' => 'Mail',  
                'table' => ‘mail',
                'type' => 'LEFT',
                'conditions' => array(
                    'Mail.user_id = User.id',
                ),
            )
        ),
        'fields' => array('User.email'),
        'limit'=>10

    );

 $returnData = $this->find('all',$options);
 return $returnData;
}

从控制器调用此方法为

$data = $this->User->getData();
print_r($data);

希望它能解决你的问题!