今天学习了下cakephp中复杂条件查询,把尝试的一些成功和失败的代码总结了下!从手册“3.7.3.10 复杂条件查询”中,只是从一个模型中获取数据,所以尝试从两个模型中获取数据!
首先简单说下模型关系:User和Note模型!关系参见Cakephp的Note项目数据结构笔记,数据结构为:
查询目的:根据搜索关键字“an”查询用户,并查询用户所有包含关键字“an”的note!好的,让我们看看视图代码:
myAdvsearchcreate("User",array('action'=>'search')); echo $form->input("q",array('label'=>'keywords:')); echo $form->end("search");?>
name | subject | created |
| | |
users控制器中需要一个search方法:function search(){};要实现查询功能的代码就写在这个方法里面!以下先给大家看看要达到搜索所使用的sql语句!
SELECT *FROM usersLEFT JOIN notes ON users.id = notes.user_idWHERE users.name LIKE '%an%'OR notes.subject LIKE '%an%'LIMIT 0 , 30
那么我们使用了如下代码,是没有达到我们的目标的!请注意分析下段代码:
$results = $this->User->find('all',array( 'conditions' => array('OR' => array('User.name LIKE' => '%'.$this->data['User']['q'].'%','Note.subject LIKE' => '%'.$this->data['User']['q'].'%'))));
使用下列代码也没有成功!
$conditions = array('User.name LIKE'=>'%'.$this->data['User']['q'].'%' );$results = $this->User->find('all', array( 'conditions' => $conditions, 'contain' => array( 'Note' => array( 'conditions' => array( 'Note.subject LIKE'=>'%'.$this->data['User']['q'].'%', ) ) ) ));
最后,我们使用sql语句查询达到了我们的目标:
function search(){ if($this->data['User']['q']){ $sql = "SELECT * FROM users AS User " . "LEFT JOIN notes AS Note On User.id = Note.user_id " . "WHERE User.name LIKE '%an%' " . "OR " . "Note.subject LIKE '%an%' "; $results = $this->User->query($sql); $this->set('results',$results); }else{ $this->set('results',null); } }
注意以上错误代码都写在if判断正确的语句块中!