Today I learned how to query complex conditions in cakephp and summarized some successful and failed code! In the manual "3.7.3.10 complex condition query", only data is obtained from a model, so we try to get data from both models! Today I learned how to query complex conditions in cakephp and summarized some successful and failed code! In the manual "3.7.3.10 complex condition query", only data is obtained from a model, so we try to get data from both models!
First, let's briefly describe the model relationship: User and Note models! For details about the relationship, see the Note project data structure notes in Cakephp. The data structure is as follows:
Purpose: to query a user based on the search keyword "an" and query all notes containing the keyword "! Okay. let's look at the View code:
MyAdvsearch
Create ("User", array ('action' => 'Search'); echo $ form-> input ("q", array ('label' => 'Keywords: '); echo $ form-> end ("search");?>The users controller requires a search method: function search () {}; write the code to implement the query function in this method! The following shows the SQL statements used for searching!
SELECT *FROM usersLEFT JOIN notes ON users.id = notes.user_idWHERE users.name LIKE '%an%'OR notes.subject LIKE '%an%'LIMIT 0 , 30
The following code is used to achieve our goal! Analyze the following code:
$results = $this->User->find('all',array('conditions' => array('OR' => array('User.name LIKE' => '%'.$this->data['User']['q'].'%','Note.subject LIKE' => '%'.$this->data['User']['q'].'%'))));
The following code is not successful!
$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'].'%',)))));
Finally, we use SQL statement queries to achieve our goal:
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);}}
Note that the above error codes are written in the if statement block to determine the correctness!