Home  >  Article  >  php教程  >  Summary of methods for querying related tables in Cakephp

Summary of methods for querying related tables in Cakephp

黄舟
黄舟Original
2016-12-20 09:35:072019browse

We can implement it in the following ways

{Query all the information containing the keyword keyword in the Note of the specified User}

1.SQL statement

SELECT * FROM Users AS User
LEFT JOIN Notes AS Note ON User.id = Note.user_id
WHERE
User.id = {$user_id}
AND
Note.subject LIKE '%{keyword}%'

Then we execute this SQL statement and use the query method of the model

$data = $this->User->query($sql);

2. Use the bindModel() and unbindModel() methods of the model

For instructions on these two methods, please refer to


http://api.cakephp.org/class/model

Our approach is

//重新绑定关联指定查询条件
 
$this->User->unbindModel('Note');
$this->User->bindModel(
    'hasMany' => array(
        'Note' => array(
            'conditions' => array(
                'Note.subject LIKE' => '%'.$keyword.'%'
            )
        )
    )
);
 
//指定主表条件获取数据
$data = $this->User->find('all',array(
    'conditions' => array(
        'User.id' => $user_id
    )
));
 
//或者
 
$data = $this->User->read(null,$user_id);

3. Using Cakephp’s core behavior (Behavior) Containable

We first create our own AppModel class and create the file /app/app_model.php

class AppModel extends Model {
 
    //加载核心行为
    var $actsAs = array('Containable');
 
}

Then we can query through such code in the controller

$this->User->contain('Note.subject LIKE' => '%'.$keyword.'%');
 
$data = $this->User->find('all',array(
    'conditions' => array(
        'User.id' => $user_id
    )
));

You can also write it directly into the find statement, similar to the following

$data = $this->User->find('all',array(
    'conditions' => array(
        'User.id' => $user_id
    ),
    'contain' => array(
        'Note' => array(
            'conditions' => array(
                'Note.subject LIKE' => '%'.$keyword.'%'
            )
        )
    )
));

Notes:

If you want to query {User.name or Note.subject all records containing the keyword keyword}

At this time, Cakephp's find method cannot be implemented This query must use the custom SQL statement introduced above, as follows:

SELECT *
FROM users AS User
LEFT JOIN notes AS Note ON User.id = Note.user_id
WHERE
User.name LIKE '%keyword%'
OR
Note.subject LIKE '%keyword%'

The above is a summary of the method of querying the association table in Cakephp. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn