A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始


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

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

1
$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%'

1 个回复

倒序浏览
奈斯,感谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马