我们可以采用下列几种方式实现
{查询指定User的Note中包含关键词keyword的所有信息}
1.SQL语句
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}%'然后我们执行这个SQL语句,使用模型的query方法
$data = $this->User->query($sql);
2.使用模型的bindModel()和unbindModel()方法
立即学习“PHP免费学习笔记(深入)”;
关于这两种方法的说明,请参照
http://api.cakephp.org/class/model
我们的做法是
//重新绑定关联指定查询条件
 
$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. 使用Cakephp的核心行为(Behavior) Containable
我们先建立自己的AppModel类,建立文件/app/app_model.php
class AppModel extends Model {
 
    //加载核心行为
    var $actsAs = array('Containable');
 
}然后我们在控制器中,可以通过这样的代码查询
$this->User->contain('Note.subject LIKE' => '%'.$keyword.'%');
 
$data = $this->User->find('all',array(
    'conditions' => array(
        'User.id' => $user_id
    )
));也可以直接写到find语句中,类似下面的
$data = $this->User->find('all',array(
    'conditions' => array(
        'User.id' => $user_id
    ),
    'contain' => array(
        'Note' => array(
            'conditions' => array(
                'Note.subject LIKE' => '%'.$keyword.'%'
            )
        )
    )
));注意事项:
如果要查询{User.name或者Note.subject包含关键词keyword的所有记录}
此时,Cakephp的find方法无法实现这个查询,必须使用上面介绍的自定义SQL语句,如下:
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%'
 以上就是Cakephp查询关联表的方法总结的内容,更多相关内容请关注PHP中文网(www.php.cn)! 
 
                        
                        PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号