PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

Cakephp查询关联表的方法总结

黄舟
黄舟 原创
2016-12-20 09:35:07 1821浏览

我们可以采用下列几种方式实现

{查询指定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()方法

关于这两种方法的说明,请参照

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)! 

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。