CakePHP复合查找条件使用'and','或'子句

时间:2012-07-06 06:25:07

标签: cakephp cakephp-2.0

我的查询是这个;

//here $u_id is id of the users table retrieved using session variable

$this->User->Request->find("all",array("conditions" =>array("request.status" => "friends" , 
"OR" => array("request.friend_id" => "$u_id","request.user_id" => "$u_id"))));

等效的SQL查询是: -

SELECT `Request`.`id`, `Request`.`user_id`, `Request`.`friend_id`, `Request`.`status`, `User`.`id`, `User`.`name`, `User`.`email`, `User`.`password`, 
FROM 
`myblog`.`requests` AS `Request` JOIN `myblog`.`users` AS `User` 
ON 
(`Request`.`friend_id` = `User`.`id`) 
WHERE  
((`request`.`friend_id` = 3) OR (`request`.`user_id` = 3)) AND `request`.`status` = 'friends'

虽然我希望在上面的SQL查询中'ON'之后的以下行获得所需的结果:

`Request`.`user_id` = `User`.`id` OR `Request`.`friend_id` = `User`.`id`

我应该在find()方法中做出哪些更改, 或者我应该改变我的模型?

我的表是:

  

用户(身份证,姓名,密码,电子邮件)
  请求(id,user_id(用户表的id),
  friend_id(用户表的id),状态)

1 个答案:

答案 0 :(得分:0)

您可以在模型中指定条件。

public $belongsTo = array('User' => array('className' => 'Request',
                                          'foreignKey' => 'user_id',
                                          'conditions' => array('OR' => array('Request.user_id' => 'User.id', 'Request.friend_id' => 'User.id')
                                         ))
                         );